简体   繁体   English

使用Shell脚本从多个文件进行数学运算

[英]make math operation from multiple files with shell scripting

I have multiple files, let's say 我有多个文件,比方说

fname1 contains: fname1包含:

red=5
green=10
yellow=2

fname2 contains: fname2包含:

red=10
green=2
yellow=2

fname3 contains: fname3包含:

red=1
green=7
yellow=4

I want to write script that read from these files, sum the numbers for each colour, and redirect the sums into new file. 我想编写从这些文件读取的脚本,将每种颜色的数字求和,然后将总和重定向到新文件中。

New file contains: 新文件包含:

red=16
green=19
yellow=8

[ awk ] is your friend : [awk]是你的朋友:

awk 'BEGIN{FS="=";}
            {color[$1]+=$2}
     END{
         for(var in color)
          printf "%s=%s\n",var,color[var]
        }' fname1 fname2 fname3 >result

should do it. 应该这样做。


Demystifying above stuff 揭秘上述东西

  • Anything that is include inside '' is the awk program. ''包含的任何内容都是awk程序。
  • Stuff inside BEGIN will be executed only once, ie in the beginning BEGIN东西只会执行一次,即在开始时
  • FS is an awk built-in variable which stands for field separator. FS是awk内置变量,代表字段分隔符。
  • Setting FS to = means awk will use = to delimit the fields/columns. 将FS设置为=表示awk将使用=分隔字段/列。
  • By default awk considers each line as a record. 默认情况下, awk将每行视为一条记录。
  • In that case you have two fields denoted by $1 and $2 in each record having = as the delimiter. 在这种情况下,每个记录中都有两个用$ 1和$ 2表示的字段,其中=用作分隔符。
  • {color[$1]+=$2} creates(if not already exist) an associative array with color name as the key and += adds the value of the field2 to this array element. {color[$1]+=$2}创建(如果尚不存在)以颜色名称作为key的关联数组, +=将field2的value添加到此数组元素。 Remember, associative arrays at the time of creation are initilized to zero. 请记住,在创建时将关联数组初始化为零。
  • This is repeated for the three files fname1, fname2, fname3 fed into awk 对于送入awk的三个文件fname1,fname2,fname3重复此操作
  • Anything inside END{} will be executed only at last, ie just before exit. END{}都只会在最后(即在退出之前)执行。
  • for(var in color) is a the style of forloop used to parse an associative array. for(var in color)是一种用于解析关联数组的forloop样式。
  • Here var will be a key and color[key] points to value. 此处var将是一个keycolor[key]指向值。
  • printf "%s=%s\\n",var,color[var] is self explained. printf "%s=%s\\n",var,color[var]是自我解释的。

Note 注意

  • If all the filenames start with fname you can even put fname* instead of fname1 fname2 fname3 如果所有文件名都以fname开头,您甚至可以输入fname*而不是fname1 fname2 fname3
  • This assumes that there are no blank lines in any file 假定任何文件中没有空行

Because your source files are valid shell code. 因为您的源文件是有效的外壳代码。 You can just source them (if they are from a trusted source) and accumulate them using Shell Arithmetic . 您可以仅获取它们(如果它们来自受信任的源),然后使用Shell Arithmetic累积它们。

#!/bin/bash

sum_red=0
sum_green=0
sum_yellow=0

for file in "$@";do
    . ${file}
    let sum_red+=red
    let sum_green+=green
    let sum_yellow+=yellow
done

echo "red=$sum_red
green=$sum_green
yellow=$sum_yellow"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM