如何合并两个文件中的行?

时间:2019-04-08 04:35:01

标签: awk filemerge

我有文件1:

1
5
4

和文件2:

44
65
56

我要归档。

1
44
5
65
4
56

谢谢

3 个答案:

答案 0 :(得分:4)

paste与自定义分隔符\n一起使用,即换行符:

paste -d '\n' file1 file2 > file.out

或GNU sed:

sed 'R file2' file1

或awk:

awk 'NR==FNR{a[NR]=$0;next} {print a[FNR]} 1' file1 file2

答案 1 :(得分:3)

paste是更好的方法,但是使用awk时,您可以使用getline在读取某些文件的同时从另一个文件读取:

awk -v f2="file2" '{print; getline < f2; print;}' file1

答案 2 :(得分:1)

请尝试以下解决方案,如果有的话,它将适用于2个以上Input_file。

awk 'FNR==NR{a[FNR]=$0;next} {a[FNR]=(a[FNR]?a[FNR] ORS:"")$0} END{for(i=1;i<=FNR;i++){print a[i]}}'  Input_file1  Input_file2


EDIT: :添加了另外1个通用解决方案,我们可以向其中传递N个文件,而不是假设所有Input_file中的行数相同,它将从所有文件中获得最大行数,并且将打印匹配的行(所有文件中都有行号),并且将打印行(最后在任何文件中的行数也更多),以防OP的文件包含这种情况。

假设我们有3个文件,分别为file1,file2和file3。

cat Input_file1
1
5
4

cat Input_file2
44
65
56

cat Input_file3
1
2
3
4
5
6

现在是代码。

awk '
prev!=FILENAME{
   count=count>prev_count?count:prev_count
}
{
   prev_count=FNR
}
FNR==1{
   prev=FILENAME
}
FNR==NR{
   a[FNR]=$0
   next
}
{
   a[FNR]=(a[FNR]?a[FNR] ORS:"")$0
}
END{
   count=count>prev_count?count:prev_count
   for(i=1;i<=count;i++){
      print a[i]
   }
}'   Input_file1  Input_file2   Input_file3

输出如下。

1
44
1
5
65
2
4
56
3
4
5
6