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

后端 未结 21 1851
没有蜡笔的小新
没有蜡笔的小新 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:41

    If Perl is an option, you can try:

    perl -0pe 's/(.*)\n(.*)\n/$1 $2\n/g' file.txt
    
    0 讨论(0)
  • 2020-11-22 15:44

    Another solutions using vim (just for reference).

    Solution 1:

    Open file in vim vim filename, then execute command :% normal Jj

    This command is very easy to understand:

    • % : for all the lines,
    • normal : execute normal command
    • Jj : execute Join command, then jump to below line

    After that, save the file and exit with :wq

    Solution 2:

    Execute the command in shell, vim -c ":% normal Jj" filename, then save the file and exit with :wq.

    0 讨论(0)
  • 2020-11-22 15:44

    You can also use the following vi command:

    :%g/.*/j
    
    0 讨论(0)
  • 2020-11-22 15:45

    "ex" is a scriptable line editor that is in the same family as sed, awk, grep, etc. I think it might be what you are looking for. Many modern vi clone/successors also have a vi mode.

     ex -c "%g/KEY/j" -c "wq" data.txt
    

    This says for each line, if it matches "KEY" perform a j oin of the following line. After that command completes (against all lines), issue a w rite and q uit.

    0 讨论(0)
  • 2020-11-22 15:46

    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
    
    0 讨论(0)
  • 2020-11-22 15:47

    Here is another way with awk:

    awk 'ORS=NR%2?FS:RS' file
    

    $ cat file
    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
    

    $ awk 'ORS=NR%2?FS:RS' file
    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
    

    As indicated by Ed Morton in the comments, it is better to add braces for safety and parens for portability.

    awk '{ ORS = (NR%2 ? FS : RS) } 1' file
    

    ORS stands for Output Record Separator. What we are doing here is testing a condition using the NR which stores the line number. If the modulo of NR is a true value (>0) then we set the Output Field Separator to the value of FS (Field Separator) which by default is space, else we assign the value of RS (Record Separator) which is newline.

    If you wish to add , as the separator then use the following:

    awk '{ ORS = (NR%2 ? "," : RS) } 1' file
    
    0 讨论(0)
提交回复
热议问题