Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

sub values

39 views
Skip to first unread message

Steve

unread,
Mar 28, 2012, 5:58:50 AM3/28/12
to
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.

Cheers,

Steve

Steve

unread,
Mar 28, 2012, 6:41:23 AM3/28/12
to
apologies, the last command should be
awk '{sub("^0 ", "NA "); print $0}'

Eric Pement

unread,
Mar 30, 2012, 1:05:58 AM3/30/12
to
On Wednesday, March 28, 2012 4:58:50 AM UTC-5, Steve wrote:
> 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.

Try this:
awk '{gsub(/\<0\>/, "NA")}; 1'

Eric

Ed Morton

unread,
Apr 2, 2012, 4:37:56 PM4/2/12
to
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.

Ed Morton

unread,
Apr 2, 2012, 5:03:18 PM4/2/12
to
Won't work if the number is 00 or 0.0 or ....

I may be reading too much into the OPs requirement to handle "all 0 values" though.

Ed.
0 new messages