如何从两个不同的文件中逐行减去

时间:2016-02-29 07:26:26

标签: bash awk sh

我有两个文件如下:

 file1 (10 lines) :
 1 0 1 0 1 1 1 1 1
 1 1 1 2 3 4 5 1 1
 ...... 
 file2 (4 lines ) :
 1 2 3 1 1 1 1 1 1 
 1 2 1 1 1 1 1 3 1
 .......

我想对file2和file1之间的file1中的每一行进行区分,并将其保存到不同的file3 $ i。可能看起来像: 对于file1的第一行

 file31 (4 lines) :
 0 2 2 1 0 0 0 0 0
 0 2 0 1 0 0 0 2 0
 ..........

更清楚。 对于file1的第一行,输出如下:

 1st row of file2 - 1st row of file1
 2nd row of file2 - 1st row of file1
 3rd row of file2 - 1st row of file1
 4th row of file2 - 1st row of file1

对于file1的第二行,输出如下:

 1st row of file2 - 2nd row of file1
 2nd row of file2 - 2nd row of file1
 3rd row of file2 - 2nd row of file1
 4th row of file2 - 2nd row of file1
对于file1中的其余行,

等等。

我尝试使用awk但找不到智能解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用此awk命令:

awk 'FNR==NR {
   for(i=1; i<=NF; i++)
      a[FNR,i]=$i
   nr1=FNR
   next
} {
   out="outfile" FNR
   for(r=1; r<=nr1; r++) {
      for(i=1; i<=NF; i++) {
         v = a[r,i] - $i
         printf "%s%s", (v>0?v:0), (i==NF)?ORS:OFS > out
      }
   }
   close(out)
}' file2 file1

此命令将为file1中的每一行输出单独的输出文件,名称为outfile1outfile2outfile3等。

<强>输出:

cat outfile1
0 2 2 1 0 0 0 0 0
0 2 0 1 0 0 0 2 0

cat outfile2
0 1 2 0 0 0 0 0 0
0 1 0 0 0 0 0 2 0