Two-line sed
Sed is a wonderful tool. However, it operates on a single line of input at a time. A simple way to overcome this, and write nice \n-expecting s///-expressions on two lines at a time is the following:
sed -re 'N; <number-of-lines-preserving s///> P; D;
E.g.
# Evaluates regexp on two input lines
echo -e "firstlineregexp\nfirstlineregexp\nsecondlineregexp\nfirstlineregexp\nfirstlineregexp\nsecondlineregexp"
| sed -re 'N; s/^(first)lineregexp\n(secondhlineregexp$/\1\n\2/; P; D;
firstlineregexp
first
second
firstlineregexp
first
second
I got to this from a working example I used:
# Removes traling commas before )-starting lines:
sed -re 'N; s/^(.*),\s*\n(\s*\).*)$/\1\n\2/; P; D;'
This snippet will:
- Read another line into the pattern space (N)
- Evaluate the s///-expression on the pattern space
- Print the first line of the pattern space (P)
- Delete the first line of the pattern space and start over (D)
This simple method does not counter whenever you want to decrease the number of lines or increase it. For this, more advanced methods are needed.
If you have any suggestions, corrections or complaints, I'm reachable at skrewz@skrewz.net.