如何逐行合并文件?

猫文件1

foo ice two 

猫文件2

 bar cream hundred 

期望的输出:

 foobar icecream twohundred 

file1和file2在我的场景中总是具有相同数量的行,以防止事情变得更容易。

这项工作的正确工具可能是paste

 paste -d '' file1 file2 

有关详细信息,请参阅man paste

通过awk方式:

 awk '{getline x<"file2"; print $0x}' file1 
  • getline x<"file2"file2读取整行并保存到x变量中。
  • print $0x使用$0打印整个行,然后使用x ,即file2的保存行。

paste是要走的路 。 如果你想检查一些其他方法,这里是一个python解决方案:

 #!/usr/bin/env python2 import itertools with open('/path/to/file1') as f1, open('/path/to/file2') as f2: lines = itertools.izip_longest(f1, f2) for a, b in lines: if a and b: print a.rstrip() + b.rstrip() else: if a: print a.rstrip() else: print b.rstrip() 

如果您的行数很少:

 #!/usr/bin/env python2 with open('/path/to/file1') as f1, open('/path/to/file2') as f2: print '\n'.join((a.rstrip() + b.rstrip() for a, b in zip(f1, f2))) 

请注意,对于不等数量的行,此行将在首先结束的文件的最后一行结束。

另外,使用纯bash (注意这将完全忽略空行):

 #!/bin/bash IFS=$'\n' GLOBIGNORE='*' f1=($(< file1)) f2=($(< file2)) i=0 while [ "${f1[${i}]}" ] && [ "${f2[${i}]}" ] do echo "${f1[${i}]}${f2[${i}]}" >> out ((i++)) done while [ "${f1[${i}]}" ] do echo "${f1[${i}]}" >> out ((i++)) done while [ "${f2[${i}]}" ] do echo "${f2[${i}]}" >> out ((i++)) done 

perl方式,易于理解:

 #!/usr/bin/perl $filename1=$ARGV[0]; $filename2=$ARGV[1]; open(my $fh1, "<", $filename1) or die "cannot open < $filename1: $!"; open(my $fh2, "<", $filename2) or die "cannot open < $filename2: $!"; my @array1; my @array2; while (my $line = <$fh1>) { chomp $line; push @array1, $line; } while (my $line = <$fh2>) { chomp $line; push @array2, $line; } for my $i (0 .. $#array1) { print @array1[$i].@array2[$i]."\n"; } 

从…开始:

 ./merge file1 file2 

输出:

 foobar icecream twohundred