[英]awk procedure in bash script
I have a task: Write a script for the summation of integers stored in the file. 我有一个任务:为存储在文件中的整数求和编写一个脚本。 Form a call script: example: sum a.txt 3 4
形成呼叫脚本:示例:sum a.txt 3 4
The input file can contain several columns of integer. 输入文件可以包含几列整数。 The individual columns are separeted be speces ora tabs.
各个列由“规范”或“制表符”分隔。 The script should sum a appropriate columns and write the result to stdout.
该脚本应汇总适当的列,并将结果写入stdout。 So when we have "sum a.txt 3 4" we need to add the number of the third and fourth columns file.
因此,当我们有“ sum a.txt 3 4”时,我们需要添加第三和第四列文件的编号。
So i do this: 所以我这样做:
#!/bin/bash
array1=( "$@" )
let LA=${#array1[@]}-1
awk '{for(i=1;i<=$LA;i++)y+=$'${array1[i]}'; print y}' a.txt
but i have an error: awk: : 1unexpected character '.' 但我有一个错误:awk::1个意外字符'。
Please help is there another way to add up the number of columns whose number are given in the procedure call script? 请帮忙,是否有另一种方法可以累加过程调用脚本中给出的列数?
if you are passing 3 arguments to sum 如果您要传递3个参数求和
#!/bin/bash
awk -v col1=$2 -v col2=$3 '{sum1 += $col1; sum2 += $col2} END{print sum1,sum2}' $1
when the script is invoked as sum a.txt 3 4
, then 当脚本作为
sum a.txt 3 4
调用时,则
$1 = a.txt
$2 = 3
$4 = 4
EDIT 编辑
If the number of columns can vary 如果列数可以变化
#!/bin/bash
filename=$1
cols=${@:2:$#}
awk -v c="$cols" '{split(c, cols, " "); for (col in cols) sum[col]+=$col} END{for (i in sum) print sum[i]}' $filename
Explanation 说明
-vc="$cols"
creates an awk variable c
and pass the column list -vc="$cols"
创建awk变量c
并传递列列表
split(c, cols, " ")
split the column list c
to obtain an array , cols split(c, cols, " ")
拆分列列表c
以获取一个数组,cols
for (col in cols) sum[col]+=$col
for each column value in cols
array find the sum, sum[col]+=$col
for (col in cols) sum[col]+=$col
cols
数组中每个列值的for (col in cols) sum[col]+=$col
找到总和, sum[col]+=$col
END{for (i in sum) print sum[i]}
print the sum
array END{for (i in sum) print sum[i]}
打印sum
数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.