awk: replace second column if not zero awk: replace second column if not zero unix unix

awk: replace second column if not zero


Remember that in awk, anything that is not 0 is true (though any string that is not "0" is also true). So:

awk '$2 { $2 = 1; print }' input > output

The $2 evaluates to true if it's not 0. The rest is obvious. This replicates your script.

If you want to print all lines, including the ones with a zero in $2, I'd go with this:

awk '$2 { $2 = 1 } 1' input > output

This does the same replacement as above, but the 1 at the end is short-hand for "true". And without a statement, the default statement of {print} is run.

Is this what you're looking for?

In action, it looks like this:

[ghoti@pc ~]$ printf 'none 0 nada\none 1 uno\ntwo 2 tvo\n'none 0 nadaone 1 unotwo 2 tvo[ghoti@pc ~]$ printf 'none 0 nada\none 1 uno\ntwo 2 tvo\n' | awk '$2 { $2 = 1 } 1'      none 0 nadaone 1 unotwo 1 tvo[ghoti@pc ~]$ 


Is this what you want?

awk '$2 != 0 {print $1, 1, $3} $2 == 0 {print}' input > output

or with sed:

sed 's/\([^ ]*\) [0-9]*[1-9][0-9]* /\1 1 /' input > output