Awk Anomaly

For discussions about programming and projects not necessarily associated with Porteus.
Bogomips
Full of knowledge
Full of knowledge
Posts: 2564
Joined: 25 Jun 2014, 15:21
Distribution: 3.2.2 Cinnamon & KDE5
Location: London

Awk Anomaly

Post#1 by Bogomips » 25 Jan 2015, 20:38

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.
Linux porteus 4.4.0-porteus #3 SMP PREEMPT Sat Jan 23 07:01:55 UTC 2016 i686 AMD Sempron(tm) 140 Processor AuthenticAMD GNU/Linux
NVIDIA Corporation C61 [GeForce 6150SE nForce 430] (rev a2) MemTotal: 901760 kB MemFree: 66752 kB

port
Samurai
Samurai
Posts: 137
Joined: 18 Feb 2016, 09:25
Distribution: Linux porteus 3.2.2 KDE
Location: Spain

Re: Awk Anomaly

Post#2 by port » 22 Feb 2016, 10:25

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

Post Reply