On 3/28/2012 5:41 AM, Steve wrote:
> On Mar 28, 11:58 am, Steve<
sbyrn...@gmail.com> wrote:
>> Hi,
>>
>> I am trying use awk to do something very simple -
>>
>> data file looks like this...
>>
>> 0 12 43
>> 12 120 30
>> 20 45 0
>> ..............
>>
>> I want substitute all 0 values with NA. I have it working the long way
>> round like so,
>>
>> awk '{sub(" 0 ", " NA "); print $0}'
>> awk '{sub(" 0", " NA"); print $0}'
>> awk '{sub("0 ", "NA "); print $0}'
>>
>> Trying to learn a bit so my question is this. Is there a simple way of
>> telling awk to treat 0 as a value, rather than a character when using
>> sub command.
No. The first argument for sub() (and gsub() and gensub()) is an RE. Period. If
you want a command that operates on strings rather than REs there's index() but
that still won't help with your example.
>>
>> Cheers,
>>
>> Steve
>
> apologies, the last command should be
> awk '{sub("^0 ", "NA "); print $0}'
What you really need in this case is a loop and forcing a numerical test (+0):
awk '{for (i=1;i<=NF;i++) if (($i)+0 == 0) $i="NA"; print }'
This will compress the white space between your fields to a single space char
but it doesn't look like that matters in your posted sample input.
Regards,
Ed.