使用shell脚本在一个文件中合并两个文件的内容

文件A:

1 3 5 7 

文件B:

 2 4 6 8 

可以使用文件A和文件B作为shell脚本的input,并得到一个文件C的输出,其内容如下:

 1 2 3 4 5 6 7 8 

使用paste按照发现的顺序交错线条:

 paste -d '\n' filea fileb 

或者使用sort来组合和排序文件:

 sort filea fileb 

只是:

 sort -n FileA FileB > FileC 

得到:

 1 2 3 4 5 6 7 8 
 $ cat > filea 1 3 5 7 $ cat > fileb 2 4 6 8 $ sort -m filea fileb 1 2 3 4 5 6 7 8 $ 

只是为了说清楚…按ctrl D在每个数字列表的末尾设置filea和fileb。 谢谢凯文

既然你说你想要一个shell解决方案,

 #!/bin/bash if [ $# -ne 2 ] ; then echo 'usage: interleave filea fileb >out' >&2 exit 1 fi exec 3<"$1" exec 4<"$2" read -u 3 line_a ok_a=$? read -u 4 line_b ok_b=$? while [ $ok_a -eq 0 -a $ok_b -eq 0 ] ; do echo "$line_a" echo "$line_b" read -u 3 line_a ok_a=$? read -u 4 line_b ok_b=$? done if [ $ok_a -ne 0 -o $ok_b -ne 0 ] ; then echo 'Error: Inputs differ in length' >&2 exit 1 fi