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



我可能会去这个错误的方式,但我已经尝试了每一个语法,我被困在最接近的错误,我可以得到。

我有一个日志文件,我想过滤到一组行,如下所示:

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

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

任何帮助非常感激,我相信有一个不那么复杂的方式来实现这一点,仍在学习。

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

(不是答案,而是格式化的注释)

当我看到一长串grep和awks(和seed等)的管道时,我总是感到不安

... | grep "Files :" | grep -v "*.*" | egrep -v "Files : [a-zA-Z]" | awk '{$1=$1}1' OFS="," | awk -F "," '{print $4}'

可以写成

... | awk '/Files : [^[:alpha:]]/ && !/*/ {print $4}'

您是否使用grep -v "*.*"来过滤带点的线,或带星号的线?因为你正在实现后者

最新更新