0

cat file.txt

...Some random string...
...String random string...
service_account_file = $HOME/easyclone/accounts/1.json
...Some random string...
...Some random string...

I just need to substitute the end part of line 3 ( 1 in this case , ie the number before string .json) with the value of a predefined variable

rjc1=999 && sed -i "3s/*\.json/$rjc1\.json/" file.txt

I tried the above command intending to replace 1.json by 999.json but it doesn't seem to work

Expected result with the above variable value

...Some random string...
...String random string...
service_account_file = $HOME/easyclone/accounts/999.json
...Some random string...
...Some random string...

Can anyone please help me to fix this small issue

Note :

  1. i didn't simply substitute 1.json in file.txt because it could be any random number originally in file.txt.
  2. Also didn't used global substitution as i need to substitute value in particular line only
Sachin
  • 1,217
  • 2
  • 11
  • 31
  • `*` is a modifier, unlike in shell patterns, where it stands on its own. `*\.json` matches literally `*.json`; did you mean `.*\.json`? That would replace the whole line, though. If you want to replace any one character, you could use `.\.json`; for "one or more digits", you could use `[[:digit:]]\{1,\}\.json`. – Benjamin W. Feb 18 '21 at 14:07

1 Answers1

2
sed -ri "3s/[[:digit:]]+\.json/$rjc1.json/" file

On the third line, substitute, one or more digits and then ".json" for the rjc1 variable followed by ".json"

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
  • @RamanSailopal Thanks for the edit but on deep testing , i have found one issue . Originally i kept it 999.json in 3rd line. Then i ran the following ```rjc1=998 && sed -r -i "3s/[[:digit:]].json/$rjc1.json/" file.txt``` to change 999.json to 998.json in 3rd line but the sed regex weirdly changed it to 99998.json – Sachin Feb 18 '21 at 14:33
  • Yeah. Make sure, you have the + after [[:digit:]] Make sure you have -r or -E as well – Raman Sailopal Feb 18 '21 at 14:34