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

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


当前回答

杀死一只狗的方法不止绞刑。[1]

awk '{key=$0; getline; print key ", " $0;}'

在引号内放入您喜欢的任何分隔符。


引用:

原本是“Plenty of ways to skin the cat”,后来变成了一个古老的、可能起源于宠物的表达,也和宠物无关。

其他回答

试试下面这句话:

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

在中间放置分隔符

"$line1 $line2";

例如,如果分隔符是|,那么:

"$line1|$line2";

sed、awk、grep的替代方案:

xargs -n2 -d'\n'

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

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

与glenn jackman使用粘贴的回答略有不同:如果-d分隔符选项的值包含多个字符,则逐个粘贴这些字符,并结合-s选项在处理相同输入文件时继续这样做。

这意味着我们可以使用任何我们想要的分隔符加上转义序列\n来一次合并两行。

使用逗号:

$ paste -s -d ',\n' infile
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

还有美元符号:

$ paste -s -d '$\n' infile
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

它不能做的是使用由多个字符组成的分隔符。

作为奖励,如果粘贴是POSIX兼容的,这将不会修改文件中最后一行的换行符,因此对于具有奇数行数的输入文件,如

KEY 4048:1736 string
3
KEY 0:1772 string

粘贴不会在最后一行添加分隔字符:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string

在我需要合并两行(为了更容易处理),但允许数据超过特定的情况下,我发现这是有用的

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

然后输出如下:

converted_data.txt

string1=x string2=y
string3
string4

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