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

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


当前回答

使用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

其他回答

awk:

awk 'NR%2{printf "%s ",$0;next;}1' yourFile

注意,在输出的末尾有一个空行。

sed:

sed 'N;s/\n/ /' yourFile

杀死一只狗的方法不止绞刑。[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";

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

使用vim的另一个解决方案(仅供参考)。

解决方案1:

打开vim vim文件名中的文件,然后执行命令:% normal Jj

这个命令很容易理解:

%:对于所有的行, Normal:执行正常命令 京晶:执行Join命令,然后跳转到线下

然后,保存文件并以:wq退出

解决方案2:

在shell中执行命令,vim -c ":% normal Jj" filename,保存文件并以:wq退出。