How to use sed for multi-line pattern replacement

· Category: Linux

Short answer

Use N to append the next line into the pattern space, enabling multi-line matching and replacement in sed.

Steps

  1. Join two lines:
sed 'N;s/
/ /' file.txt
  1. Replace across lines:
sed 'N;s/start
end/replaced/' file.txt
  1. Use a loop to read entire file:
sed ':a;N;$!ba;s/
/ /g' file.txt

Tips

  • N adds the next line; n prints and reads the next line.
  • :a;N;$!ba is a common idiom to slurp the entire file.
  • For complex multi-line edits, consider awk or Perl.

Common issues

  • The last line may not have a trailing newline; N can fail.
  • Complex escapes make sed scripts hard to read; add comments.