Tip #539 Using sed across multiple lines
Sometimes when using sed you find that you need to match across line endings, this can be achieved by getting sed to match the first line and then pulling a second line into the buffer with the N command.For example, if we have a file:
$ cat foo This is a sample hello world file.
And want to change 'hello world' to 'hello shell-fu' we need to replace across lines. This can be done with the following command:
:~$ cat foo | sed '/hello$/N;s/hello\nworld/hello\nshell-fu/' This is a sample hello shell-fu file.
Here sed first looks for lines which end with 'hello' then reads the next line, finally replacing 'hello\nworld' with 'hello\nshell-fu'.
This also has a lot of other uses, for example converting double line spaced files to single:
cat doublespace | sed '/^$/N;s/\n$//g'
- TAGS:
- sed
alias aptitude at awk bash bc cal cat cd colrm comm cp csh curl cut date dd df dialog diff dirname dpkg du fc find fuser grep gs gzip history iconv kill ksh last less ln ls lsof lynx m4 md5sum mkdir mkfifo mkisofs mv mysql nc netstat openssl OSX perl ping popd ps pushd python read redirection rm scp screen sed sort ssh stat sudo svn tail tar tee test top tr uniq vim wc wget xargs