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

后端 未结 21 1849
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 15:14

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         


        
相关标签:
21条回答
  • 2020-11-22 15:48

    Simplest way is here:

    1. Remove even lines and write it in some temp file 1.
    2. Remove odd lines and write it in some temp file 2.
    3. Combine two files in one by using paste command with -d (means delete space)

    sed '0~2d' file > 1 && sed '1~2d' file > 2 && paste -d " " 1 2
    
    0 讨论(0)
  • 2020-11-22 15:48

    You can use xargs like this:

    xargs -a file
    
    0 讨论(0)
  • 2020-11-22 15:49

    A slight variation on glenn jackman's answer using paste: if the value for the -d delimiter option contains more than one character, paste cycles through the characters one by one, and combined with the -s options keeps doing that while processing the same input file.

    This means that we can use whatever we want to have as the separator plus the escape sequence \n to merge two lines at a time.

    Using a comma:

    $ paste -s -d ',\n' infile
    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
    

    and the dollar sign:

    $ paste -s -d '$\n' infile
    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
    

    What this cannot do is use a separator consisting of multiple characters.

    As a bonus, if the paste is POSIX compliant, this won't modify the newline of the last line in the file, so for an input file with an odd number of lines like

    KEY 4048:1736 string
    3
    KEY 0:1772 string
    

    paste won't tack on the separation character on the last line:

    $ paste -s -d ',\n' infile
    KEY 4048:1736 string,3
    KEY 0:1772 string
    
    0 讨论(0)
提交回复
热议问题