onetrueawk / awk

One true awk

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

gsub and sub does not take "&"

hallenstal opened this issue · comments

awk version 20200816 on Mac 13.0.1

get the following using sub:
awk 'BEGIN {s="qwerty xxxx"; s2=s; s3=s; sub(/xxxx/,"&",s); sub(/xxxx/,"\046",s2);sub(/xxxx/,"!!",s3);print s,s2,s3}'
qwerty xxxx qwerty xxxx qwerty !!

and sub:
awk 'BEGIN {s="qwerty xxxx"; s2=s; s3=s; gsub(/xxxx/,"&",s); gsub(/xxxx/,"\046",s2);gsub(/xxxx/,"!!",s3);print s,s2,s3}'
qwerty xxxx qwerty xxxx qwerty !!

is there a reason why you can't substitute to "&"?

some more interesting stuff regarding "&"
awk 'BEGIN {s="qwerty xxxx"; s2=s; s3=s; sub(/xxxx/,"&&&&&&&&&",s);;print s}'
qwerty xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

workaround
awk 'BEGIN {s="qwerty xxxx579"; match(s,/xxxx/); s=substr(s,1,RSTART-1) "&" substr(s,RSTART+RLENGTH);print s}'

I'm not sure I understand this discussion. do you feel that this behaviour violates the standard, or is inconsistent between the implementations?

command:
awk 'BEGIN {s="qwerty xxxx"; s2=s; s3=s; sub(/xxxx/,"&",s); sub(/xxxx/,"\046",s2);sub(/xxxx/,"!!",s3);print s,s2,s3}'

result:
qwerty xxxx qwerty xxxx qwerty !!

this shows that sub() does not substitute regular expression for "&", but it does it for all other characters e.g. "!!" as seen by the example above. "xxxx" is not replaced when replacement string is "&" but it is replaced if other string e.g. "!!"

try...

you do realize "&" is special, right?

"in a substitution performed by either sub(r, s, t) or gsub(r, s, t), any occurrence of the character & in s will be replaced by the substring matched by r."