Total variable in awk 'if condition' under 'for loop'

I have a file with three columns (n ​​= 3) and FS = "" (file1.txt):

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

Here I would like to give an “if condition” in awkfor each column, where it will check the condition and return a value of 1 or 0 (depending on the result) and store it in another variable, for example:

#!/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

In this case, the desired result would be:

cat output.txt
2
3
3

What I get without problems.

, 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+=xn print xn ? , ?

+4
2

awk:

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

  • Awk (?:), awk If Else Statement. , 1 , , 2.

+3

, , :

$ awk '
{
    sum = 0
    for (i=1; i<=NF; i++) {
        sum += ($i == 0 : 0 : 1)
        # or `sum += ($i ? 1 : 0)`
        # or `sum += ($i != 0)`
    }
    print sum

}
' file
2
3
3

GNU awk \<... \> :

$ gawk '{ print gsub(/\<[^0][^ ]*\>/,1) }' file
2
3
3

, @anubhava, parens , awks, .

+2

Source: https://habr.com/ru/post/1527184/


All Articles