Replacing multiple lines in sed or awk

12,282

Sed is quite bad at this, because it operates one line at a time. The only decent technique I've ever seen to do this is this one, which involves storing the entire file in sed's hold buffer and then operating on it all at once:

sed -n '1h;1!H;${g;s/search/replace/;p;}'

If you can, it's much easier to use perl to accomplish this:

perl -0pe 's/search/replace/'

search can contain \ns to represent newlines

Share:
12,282

Related videos on Youtube

jimmij
Author by

jimmij

Vanitas vanitatum et omnia vanitas. Libera temet ex inferis.

Updated on September 17, 2022

Comments

  • jimmij
    jimmij over 1 year

    I'm trying to use sed or awk to replace 5 lines in a smb file but I just don't have any idea how to deal with the newlines.

    • Admin
      Admin over 13 years
      f course, sed and awk can do this, but I'm having a little trouble understaning exactly what your question is. What exactly is causing you trouble? Inserting new lines? Replacing them?
  • Lazer
    Lazer over 13 years
    +1 for the sed multiliner.
  • Michael Mrozek
    Michael Mrozek over 9 years
    @Michael -0 sets the record separator to null, so the whole file will be read at once instead of line-by-line. -p makes it print the result after the substitution. -e has it take the next argument as the expression to run, and s/search/replace/ is that expression