onetrueawk / awk

One true awk
Other
1.98k stars 159 forks source link

gsub and sub does not take "&" #172

Closed hallenstal closed 1 year ago

hallenstal commented 1 year ago

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 "&"?

hallenstal commented 1 year ago

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

hallenstal commented 1 year ago

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

plan9 commented 1 year ago

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

hallenstal commented 1 year ago

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...

plan9 commented 1 year ago

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."