Joining even and odd lines in a text file
Today I had to join even and odd lines in a text file. This cannot be done elegantly (i.e. withouth auxiliary variables and counters) in either Perl or awk so I turned to sed.
Short theory of how sed operates: it reads the current line in the pattern space and applies a command on the line if the line matches the address. There is also an auxiliary space called the hold space. After reading the sed manual, I came with the following solution:
sed -n -e '1~2h ; 2~2 { x ; G ; s/\n/ /; p}' file.txt > out.txt
The -n instructs sed to suppress the default output. The 1~2 is a
GNU extension and specifies lines that give remainder of 1 when divided
by 2. Thus, the first command copies the odd line into the hold space
(the h command). The second command does the following:
- Exchange the hold space and the pattern space (
x). Thus, the current (even) line is now in the hold space. Gappends newline to the pattern space and after it the contents of the hold space - now we have concatenated the two lines, but with an extra newline.s/\n/ /is a regular expression that replaces the appended newline with a space.pprints the contents of the pattern space.{}group the commands matching the address.