我有一个如下格式的文本文件。第一行是“KEY”,第二行是“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

我需要这个值和键在同一行。所以输出应该是这样的…

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

如果我可以使用一些分隔符,如$或:

KEY 4048:1736 string , 3

我如何将两条线合并成一条?


当前回答

下面是另一种使用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

其他回答

sed、awk、grep的替代方案:

xargs -n2 -d'\n'

当您想要连接N行并且只需要以空格分隔的输出时,这是最好的方法。

我最初的答案是xargs -n2,它在单词而不是行上分离。-d (GNU xargs选项)可用于按任何奇异字符分割输入。

你可以像这样使用awk来合并2对行:

awk '{ if (NR%2 != 0) line=$0; else {printf("%s %s\n", line, $0); line="";} } \
     END {if (length(line)) print line;}' flle

使用vim的另一种方法是:

:g/KEY/join

这将对所有包含KEY字的行应用一个连接(到它下面的行)。结果:

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

"ex"是一个可脚本化的行编辑器,与sed、awk、grep等属于同一家族。我觉得这可能就是你要找的东西。许多现代vi克隆/后继者也有一个vi模式。

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

这就是说,对于每一行,如果它匹配"KEY"执行下一行的j。该命令完成后(针对所有行),发出一个w rite和q uit。

如果Perl是一个选项,您可以尝试:

perl -0pe 's/(.*)\n(.*)\n/$1 $2\n/g' file.txt