bash - 管道 awk 输出以添加到循环内的变量

标签 bash variables awk floating-point 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

我所拥有的代码会让我走到这一步,但是,我想使用 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

错误信息:

-bash: 0=1: command not found
-bash: 1=4: command not found
-bash: 4=14: command not found
-bash: 14=268: command not found

我尝试了几种不同的加法语法,但我觉得这与我尝试提供的内容有关,而不是加法本身。 目前这只是整数值,但我也希望用 float 来执行它。

非常感谢任何帮助,我相信有一种不那么复杂的方法可以实现这一目标,仍在学习中。

最佳答案

您可以在 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

输出:

Total : 268 9 8 9 8

这里的 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.

关于bash - 管道 awk 输出以添加到循环内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32339931/

相关文章:

python - 为什么我不能向字典添加更多键? - Python

linux - 如何使用linux命令提取与文本文件中特定字段匹配的文本

linux - 找不到 bash 脚本命令

python - 移动包含旧文件的目录的简单方法

linux - 如何使用 sed 识别多行中的模式

mysql - 使用@variable_Name时如何更改变量类型?

c - 堆栈变量损坏? C

bash awk 整数

bash - awk NF 文件名是如何工作的?

bash - 带有 unicode 文件路径的 runco​​mmand (haskell)