/123/ {a=""} # last #/123/,/456/ {a=(a=="") ? $0 : a RS $0} # first /123/,/456/ {a=(a=="") ? $0 : a RS $0} /456/ {exit} END { print a }