Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: replace second column if not zero

I'm trying to use awk to check the second column of a three column set of data and replace its value if it's not zero. I've found this regex to find the non-zero numbers, but I can't figure out how to combine gsub with print to replace the contents and output it to a new file. I only want to run the gsub on the second column, not the first or third. Is there a simple awk one-liner to do this? Or am I looking at doing something more complex? I've even tried doing an expression to check for zero, but I'm not sure how to do an if/else statement in awk.

The command that I had semi-success with was:

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

The problem is that it didn't print out the row if the second column was zero. This is where I thought either gsub or an if/else statement would work, but I can't figure out the awk syntax. Any guidance on this would be appreciated.

like image 887
opes Avatar asked Dec 20 '22 12:12

opes


1 Answers

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 nada
one 1 uno
two 2 tvo
[ghoti@pc ~]$ printf 'none 0 nada\none 1 uno\ntwo 2 tvo\n' | awk '$2 { $2 = 1 } 1'      
none 0 nada
one 1 uno
two 1 tvo
[ghoti@pc ~]$ 
like image 71
ghoti Avatar answered Dec 30 '22 09:12

ghoti