如何从linux中的两个文件添加一行的每个元素

时间:2014-03-22 06:41:19

标签: linux shell

我想编写shell脚本,其功能如下所述

  1. cat file1和file2,其中包含x个行数和列数(等于行数和列数)。两个文件都已创建。
  2. 脚本应该从file1和file2添加(每个元素的总和值)每一行的列元素,并生成输出为file3。 file1-: 10,10,10,10 11,11,11,11 file2-: 5,5,5,5 11,11,11 file3会有输出 - : 15,15,15,15 22,22,22,22

2 个答案:

答案 0 :(得分:3)

由于您似乎知道x,列数,您可以简单地总结一下。例如,使用x=4

--- script.sh ---
#!/bin/bash    
while true; do
  read -r c1 c2 c3 c4 <&3
  read -r d1 d2 d3 d4 <&4
  if [ -z "$c1" -o -z "$d1" ]; then
    break
  fi
  echo "$(($c1 + $d1)) $(($c2 + $d2)) $(($c3 + $d3)) $(($c4 + $d4))" >>3.txt
done 3<1.txt 4<2.txt

这是一个示例运行:

$ ./script.sh && cat 1.txt 2.txt 3.txt
1 2 3 4
5 6 7 8
9 9 9 9

1 1 1 1
1 1 1 1
1 1 1 1

2 3 4 5
6 7 8 9
10 10 10 10

答案 1 :(得分:0)

我知道你要求一个shell脚本,但我发现使用python很容易实现这种任务。

所以万一它可以帮助任何人,这里有一个快速的python脚本。此脚本支持任意数量的输入文件(一个或多个):

#! python
import sys
if len(sys.argv) <= 1:
    raise RuntimeError('usage: %s file1 file2' % sys.argv[0])
for lines in zip(sys.args[1:]):
   print sum( float(line.strip()) for line in lines )