How to merge every two lines into one from the command line?

Solution 1:

paste is good for this job:

paste -d " "  - - < filename

Solution 2:

awk:

awk 'NR%2{printf "%s ",$0;next;}1' yourFile

note, there is an empty line at the end of output.

sed:

sed 'N;s/\n/ /' yourFile

Solution 3:

Alternative to sed, awk, grep:

xargs -n2 -d'\n'

This is best when you want to join N lines and you only need space delimited output.

My original answer was xargs -n2 which separates on words rather than lines. -d (GNU xargs option) can be used to split the input by any singular character.

Solution 4:

There are more ways to kill a dog than hanging. [1]

awk '{key=$0; getline; print key ", " $0;}'

Put whatever delimiter you like inside the quotes.


References:

  1. Originally "Plenty of ways to skin the cat", reverted to an older, potentially originating expression that also has nothing to do with pets.

Solution 5:

Here is my solution in bash:

while read line1; do read line2; echo "$line1, $line2"; done < data.txt