如何将每两行合并为一行

如何将每两行合并为一行

我有这个文件:

~path1/file1.txt ~path1/file1_newname
par1 par2 par 53
~path1/file2.txt ~path1/file2_newname
par1 par2
~path1/file3.txt ~path1/morepath/file3_newname
par31 par121
~path2/file1.txt ~path2/file1_newname
par87
~path2/file3.txt ~path2/file3_newname
par1
~path2/file4.txt ~path2/file4_newname
par2 par3 par4
~path3//path4/file3.txt ~path3/file4_newname
par13

我希望最后能得到这个:

~path1/file1.txt ~path1/file1_newname par1 par2 par 53
~path1/file2.txt ~path1/file2_newname par1 par2
~path1/file3.txt ~path1/morepath/file3_newname par31 par121
~path2/file1.txt ~path2/file1_newname par87
~path2/file3.txt ~path2/file3_newname par1
~path2/file4.txt ~path2/file4_newname par2 par3 par4
~path3//path4/file3.txt ~path3/file4_newname par13

我试图通过它进行排序sort -k,但没有成功。

我应该怎么做才能对其进行排序?

编辑以在回答后显示新模式:

~/path1/file1.cob ~/path1/file1_namename
 param1 param2 param90 ~/path1/file2.cob ~/path1/file2_namename
 param1 param2
~/path1/file3.cob ~/path1/path2/file3_namename
 param15 param124 ~/path2/file1.cob ~/path2/file1_namename.cob
 param55
~/path2/file2.cob ~/path2/file2_namename.cob
 param1 ~/path2/file5.cob ~/path4/file2_namename.cob param23
~/path3/file2.cob ~/path2/file4_namename.cob
 param2 param3 param4 ~/path3/path1/file3.cob ~/path3/file2_namename.cob
 param3

答案1

请注意,这与排序无关。它只是将线条连接在一起。

这些解决方案假设您始终希望成对连接线路。

使用标准sed

$ sed 'N; s/\n/ /' file
~path1/file1.txt ~path1/file1_newname par1 par2 par 53
~path1/file2.txt ~path1/file2_newname par1 par2
~path1/file3.txt ~path1/morepath/file3_newname par31 par121
~path2/file1.txt ~path2/file1_newname par87
~path2/file3.txt ~path2/file3_newname par1
~path2/file4.txt ~path2/file4_newname par2 par3 par4
~path3//path4/file3.txt ~path3/file4_newname par13

简短的sed编辑脚本将读取一行并使用命令附加下一行N。附加的行将被添加到带有嵌入换行符的模式空间(“工作缓冲区”)中,因此在打印该行之前将其替换为带有替换的空格。

或者,与paste

$ paste -d ' ' - - <file
~path1/file1.txt ~path1/file1_newname par1 par2 par 53
~path1/file2.txt ~path1/file2_newname par1 par2
~path1/file3.txt ~path1/morepath/file3_newname par31 par121
~path2/file1.txt ~path2/file1_newname par87
~path2/file3.txt ~path2/file3_newname par1
~path2/file4.txt ~path2/file4_newname par2 par3 par4
~path3//path4/file3.txt ~path3/file4_newname par13

这要求paste产生两列输出,中间有一个空格。这些列是从输入中的行中读取的,给出了成对连接行的效果。

awk

$ awk '{ getline nextline; print $0, nextline }' file
~path1/file1.txt ~path1/file1_newname par1 par2 par 53
~path1/file2.txt ~path1/file2_newname par1 par2
~path1/file3.txt ~path1/morepath/file3_newname par31 par121
~path2/file1.txt ~path2/file1_newname par87
~path2/file3.txt ~path2/file3_newname par1
~path2/file4.txt ~path2/file4_newname par2 par3 par4
~path3//path4/file3.txt ~path3/file4_newname par13

答案2

如果我理解正确,我认为这对你有用(使用 GNU sed):

sed '1~2N;s/\n/ /' file

相关内容