Cra*_*155 3 variables floating-point bash awk addition
我可能会以错误的方式解决这个问题,但我已经尝试了所有语法,而且我遇到了最接近的错误.
我有一个日志文件,我想在其中过滤到一组行,如下所示:
Files : 1 1 1 1 1
Files : 3 3 4 4 5
Files : 10 4 2 3 1
Files : 254 1 1 1 1
Run Code Online (Sandbox Code Playgroud)
我的代码将使我达到这一点,但是,我想使用awk来执行所有第一个数字列的添加,在这个实例中给出268作为输出(然后在其他列上执行类似的任务).
我试图将awk输出传递到循环中以执行最后一步,但它不会添加值,抛出错误.我认为这可能是由于awk将条目作为字符串处理,但由于bash没有强类型,它应该无关紧要?
无论如何,代码是:
x=0;
iconv -f UTF-16 -t UTF-8 "./TestLogs/rbTest.log" | grep "Files :" | grep -v "*.*" | egrep -v "Files : [a-zA-Z]" |awk '{$1=$1}1' OFS="," | awk -F "," '{print $4}' | while read i;
do
$x=$((x+=i));
done
Run Code Online (Sandbox Code Playgroud)
错误信息:
-bash: 0=1: command not found
-bash: 1=4: command not found
-bash: 4=14: command not found
-bash: 14=268: command not found
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的添加语法,但我觉得这与我试图提供的内容有关,而不是添加本身.目前这只是整数值,但我也希望用浮点数来执行它.
任何帮助非常感谢,我相信有一个不太复杂的方式来实现这一点,仍在学习.
你可以在awk中做计算:
awk '{for (c=3; c<=NF; c++) sum[c]+=$c} END{printf "Total : ";
for (c=3; c<=NF; c++) printf "%s%s", sum[c], ((c<NF)? OFS:ORS) }' file
Run Code Online (Sandbox Code Playgroud)
输出:
Total : 268 9 8 9 8
Run Code Online (Sandbox Code Playgroud)
这sum是一个关联数组,它为#3以后的每一列保存总和.
命令分手:
for (c=3; c<=NF; c++) # Iterate from 3rd col to last col
sum[c]+=$c # Add each col value into an array sum with index of col #
END # Execute this block after last record
printf "Total : " # Print literal "Total : "
for (c=3; c<=NF; c++) # Iterate from 3rd col to last col
printf "%s%s", # Use printf to format the output as 2 strings (%s%s)
sum[c], # 1st one is sum for the given index
((c<NF)? OFS:ORS) # 2nd is conditional string. It will print OFS if it is not last
# col and will print ORS if it is last col.
Run Code Online (Sandbox Code Playgroud)