[英]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 揭秘上述东西
''
is the awk program. ''
包含的任何内容都是awk程序。 BEGIN
will be executed only once, ie in the beginning BEGIN
东西只会执行一次,即在开始时 =
means awk will use =
to delimit the fields/columns. 将FS设置为=
表示awk将使用=
分隔字段/列。 awk
considers each line as a record. 默认情况下, awk
将每行视为一条记录。 =
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. 请记住,在创建时将关联数组初始化为零。 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样式。 var
will be a key
and color[key]
points to value. 此处var
将是一个key
而color[key]
指向值。 printf "%s=%s\\n",var,color[var]
is self explained. printf "%s=%s\\n",var,color[var]
是自我解释的。 Note 注意
fname
you can even put fname*
instead of fname1 fname2 fname3
如果所有文件名都以fname
开头,您甚至可以输入fname*
而不是fname1 fname2 fname3
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.