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

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

    perl -0pE 's{^KEY.*?\K\s+(\d+)$}{ $1}msg;' data.txt > data_merged-lines.txt
    

    -0 gobbles the whole file instead of reading it line-by-line;
    pE wraps code with loop and prints the output, see details in http://perldoc.perl.org/perlrun.html;
    ^KEY match "KEY" in the beginning of line, followed by non-greedy match of anything (.*?) before sequence of

    1. one or more spaces \s+ of any kind including line breaks;
    2. one or more digit (\d+) which we capture and later re-insert as $1;

    followed by the end of line $.

    \K conveniently excludes everything on its left hand side from substitution so { $1} replaces only 1-2 sequence, see http://perldoc.perl.org/perlre.html.

提交回复
热议问题