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
- Join two lines:
sed 'N;s/
/ /' file.txt
- Replace across lines:
sed 'N;s/start
end/replaced/' file.txt
- Use a loop to read entire file:
sed ':a;N;$!ba;s/
/ /g' file.txt
Tips
Nadds the next line;nprints and reads the next line.:a;N;$!bais a common idiom to slurp the entire file.- For complex multi-line edits, consider
awkor Perl.
Common issues
- The last line may not have a trailing newline;
Ncan fail. - Complex escapes make sed scripts hard to read; add comments.