Search code examples
bashawksedmergegrep

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


I have a text file with the following format. The first line is the "KEY" and the second line is the "VALUE".

KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1

I need the value in the same line as of the key. So the output should look like this...

KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1

It will be better if I could use some delimiter like $ or ,:

KEY 4048:1736 string , 3

How do I merge two lines into one?


Solution

  • 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