gpt4 book ai didi

bash - awk 'if condition'下的sum变量 'for loop'

转载 作者:行者123 更新时间:2023-11-29 09:12:05 24 4
gpt4 key购买 nike

我有一个包含 3 列 (n=3) 且 FS = ""(file1.txt) 的文件:

cat file1.txt
3.1 6.6 0
2.4 7.1 4.9
5.7 1.2 6.1

在这里,我想在 awk 中为每一列提供一个“if 条件”,它将在其中测试一个条件并返回值 1 或 0(取决于结果)和将其存储在另一个变量中,例如:

#!/bin/bash

#code1
awk '{

if ($1 != 0)

{ x1 = 1 }
else
{ x1 = 0}


if ($2 != 0)

{ x2 = 1 }
else
{ x2 = 0}


if ($3 != 0)

{ x3 = 1 }
else
{ x3 = 0}

x = x1 + x2 + x3
print x;

}' file1.txt > output.txt

在这种情况下所需的输出是:

cat output.txt
2
3
3

我得到的没有任何问题。

考虑这样一种情况,其中不是有 3 列,而是有 10 列 (n=10),并且相同的 if 条件将应用于每一列。在这种情况下,我想运行一个 for 循环,在该循环下定义相同的 if 条件。但我认为我在指定第 n 个字段时出错。还有如何计算 xn 个变量的总和 (x1 + X2 + X3...X10)。到目前为止,这是我尝试过的:

   awk '{
for (n=1; n<=10; n++)

if ($n != 0)

{ xn = 1 }

else

{ xn = 0 }

xn+=xn
print xn;

}' file1_10fields.txt > output_10fields.txt

这没有给我正确的输出。我在哪里犯了错误?有没有更优雅的方法来做到这一点?xn+=xnprint xn 应该在循环之外吗?另外,求和的正确方法是什么?

最佳答案

你可以使用这个 awk:

awk '{sum=0; for (i=1; i<=NF; i++){sum += $i ? 1 : 0} print sum}' file
2
3
3

  • Read more about ternary operator

    Awk has conditional operator i.e ternary operator ( ?: ) whose feature is similar to the awk If Else Statement. If the conditional-expression is true, action1 will be performed and if the conditional-expression is false action2 will be performed.

关于bash - awk 'if condition'下的sum变量 'for loop',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com