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

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

    paste is good for this job:

    paste -d " "  - - < filename
    
    0 讨论(0)
  • 2020-11-22 15:32

    You can use awk like this to combine ever 2 pair of lines:

    awk '{ if (NR%2 != 0) line=$0; else {printf("%s %s\n", line, $0); line="";} } \
         END {if (length(line)) print line;}' flle
    
    0 讨论(0)
  • 2020-11-22 15:34

    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 can be used to split the input by any single character.

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

    In the case where I needed to combine two lines (for easier processing), but allow the data past the specific, I found this to be useful

    data.txt

    string1=x
    string2=y
    string3
    string4
    
    cat data.txt | nawk '$0 ~ /string1=/ { printf "%s ", $0; getline; printf "%s\n", $0; getline } { print }' > converted_data.txt
    

    output then looks like:

    converted_data.txt

    string1=x string2=y
    string3
    string4
    
    0 讨论(0)
  • 2020-11-22 15:39

    A more-general solution (allows for more than one follow-up line to be joined) as a shell script. This adds a line between each, because I needed visibility, but that is easily remedied. This example is where the "key" line ended in : and no other lines did.

    #!/bin/bash
    #
    # join "The rest of the story" when the first line of each   story
    # matches $PATTERN
    # Nice for looking for specific changes in bart output
    #
    
    PATTERN='*:';
    LINEOUT=""
    while read line; do
        case $line in
            $PATTERN)
                    echo ""
                    echo $LINEOUT
                    LINEOUT="$line"
                            ;;
            "")
                    LINEOUT=""
                    echo ""
                    ;;
    
            *)      LINEOUT="$LINEOUT $line"
                    ;;
        esac        
    done
    
    0 讨论(0)
  • 2020-11-22 15:39

    Try the following line:

    while read line1; do read line2; echo "$line1 $line2"; done <old.txt>new_file
    

    Put delimiter in-between

    "$line1 $line2";
    

    e.g. if the delimiter is |, then:

    "$line1|$line2";
    
    0 讨论(0)
提交回复
热议问题