#!/bin/bash line=${1:?} regex=${2:-1} sed -E -e "/$regex/{s/.*/$line/;:a;n;ba;q}" -e "\$a $line"