Kenny McCormack <
gaz...@shell.xmission.com> wrote:
> In article <
201303111...@webuse.net>,
> Ed Morton <
morto...@gmail.com> wrote:
> >pop <
p_...@hotmail.com> wrote:
> >
> ><snip>
> >> to expand on what was intended: toggle the first digit of
> >> $0 as:
> >> x=substr($0,1,1); $0=(++x%2) substr($0,2); ...
> >> my original intent was to do it:
> >> $0=(++substr($0,1,1)%2) substr($0,2)
> >> which obviously is incorrect (in gawk)
> >
> >You were close, the right syntax to do that is simply:
> >
> > $0=(substr($0,1,1)+1)%2 substr($0,2)
>
> Or, somewhat more simply (Note that I had suggested this earlier):
>
> # Note the absence of many (lots) of references to $0
> sub(/./,1-substr($0,1,1))
>
> (I think I got that right... 1-X will toggle 0 to 1 and 1 to 0)
Yes, it does that but it doesn't quite do what the OP was attempting as it
doesn't necessarily produce 0 or 1 the first time it's used:
$ echo "92" | awk '{ $0=(substr($0,1,1)+1)%2 substr($0,2) }1'
02
$ echo "92" | awk '{ sub(/./,1-substr($0,1,1)) }1'
-82
It's hard to say if that matters or not without some sample input and expected
output. If it did matter then following your example but adding in the OPs mod 2
operation we could go with either of these:
$ echo "92" | awk '{ sub(/./,(1-substr($0,1,1))%2) }1'
02
$ echo "92" | awk '{ sub(/./,(substr($0,1,1)+1)%2) }1'
02
Then it would still not work quite the same for empty input records:
$ echo "" | awk '{ sub(/./,(substr($0,1,1)+1)%2) }1'
$ echo "" | awk '{ $0=(substr($0,1,1)+1)%2 substr($0,2) }1'
1
which could be corrected as:
$ echo "" | awk '{ sub(/.?/,(substr($0,1,1)+1)%2) }1'
1
but I'm probably over-thinking...