0

I have a text file filename for which I want to substitute a certain numerical string in row row_numby another one that starts with leading zeros. That row is:

"uuid": "34ba55d4-42fd-448e-862a-f1515"

And I would like to substitute the last four digits so that the desired end result is:

"uuid": "34ba55d4-42fd-448e-862a-f0155"

The command I am using is:

gawk  'NR=='$row_num'{gsub(/'1515'/,'0155')};1' filename > tmp && mv tmp filename

The problem is that linux interprets 0155 as an octal number due to the leading zero and returns:

"uuid": "34ba55d4-42fd-448e-862a-f109"

Resolving the interpretation by adding 10# to 0155 does not resolve my issue because then it is evaluated and the zero is avoided, yielding:

"uuid": "34ba55d4-42fd-448e-862a-f155"

How can I make the substitution so that I obtain the desired output?

I would like the solution to be general so that it also works in the case where the first element is nonzero, for which my provided solution does work.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 2
    Why are you exposing the pattern / replacement to interpretation by the shell at all? instead of something like gawk -v row_num="$row_num" 'NR==row_num {sub(/1515/,"0155")};1' filename – steeldriver Nov 15 '19 at 03:20
  • In this case you are right. I used the single quotes because I may want to use the replacement when the strings are stored in variables. E.g. val=1515 and val2=0155. Then, I would need to use the single quotes to evaluate them right? This version of your response actually worked for me: gawk -v row_num="$row_num" 'NR==row_num {sub(/'val'/,"'$val2'")};1' filename. Thank you! – Bremsstrahlung Nov 15 '19 at 05:18
  • If you need to pass shell variables for the pattern and/or replacement, you should do so using -v like I showed for the row_num or use ENVIRON or ARGV. See for example Use a shell variable in awk – steeldriver Nov 15 '19 at 11:31

0 Answers0