How to merge every two lines into one from the com

2019-01-01 03:24发布

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?

标签: bash awk sed grep
20条回答
无与为乐者.
2楼-- · 2019-01-01 03:30

paste is good for this job:

paste -d " "  - - < filename
查看更多
十年一品温如言
3楼-- · 2019-01-01 03:30

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
查看更多
孤独总比滥情好
4楼-- · 2019-01-01 03:31

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
查看更多
无色无味的生活
5楼-- · 2019-01-01 03:32

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";
查看更多
不流泪的眼
6楼-- · 2019-01-01 03:33
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.

查看更多
不再属于我。
7楼-- · 2019-01-01 03:34

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
查看更多
登录 后发表回答