Skip to main content

You can but it's difficult. I recommend switching to a different tool. If there's a regular expression that never matches any part of the text you want to replace, you can use it as an awk record separator in GNU awk.

awk -v RS='a' '{gsub(/hello/, "world"); print}' 

If there are never two consecutive newlines in your search string, you can use awk's "paragraph mode" (one or more blank lines separate records).

awk -v RS='' '{gsub(/hello/, "world"); print}' 

An easy solution is to use Perl and load the file fully into memory.

perl -0777 -e 's/hello/world/g' 
Gilles 'SO- stop being evil'
  • 866.1k
  • 205
  • 1.8k
  • 2.3k