Page 1 of 1

Awk Anomaly

Posted: 25 Jan 2015, 20:38
by Bogomips
Don't see how this can be explained as not being a bug :unknown:

Code: Select all

guest@porteus:~$ awk 'BEGIN{print "+"x y"+"; print index(x,y)}'
++
1
guest@porteus:~$ awk 'BEGIN{x="lib";print "+"x y"+"; print index(x,y)}'
+lib+
1
guest@porteus:~$ awk 'BEGIN{x="lib";print "+"x y"+"; print index(x,"l")}'
+lib+
1
Logically the null string should match position zero, giving an index of 0, as one would expect.

Re: Awk Anomaly

Posted: 22 Feb 2016, 10:25
by port
It's not an anomaly but normal behaviour.

awk string begin in index 1 not 0. Function index returns the position of first character of string to find that is a number >= 1 or number 0 if no occurrence found.

When you look for null string in another string, you always find the null string at first position ;-)

Code: Select all

guest@porteus:~$ awk 'BEGIN{x="a non-empty string"; print index(x,"");}'
1
guest@porteus:~$ awk 'BEGIN{x=""; print index(x,"");}'
1
guest@porteus:~$ awk 'BEGIN{x="hal"; print index(x,"p");}'
0
guest@porteus:~$ awk 'BEGIN{x=""; print index(x,"p");}'
0