Home > Net >  To replace a immediate text after pattern match in Linux shell using sed
To replace a immediate text after pattern match in Linux shell using sed

Time:04-08

Content of a json file

"iso_checksum": "md5:32fdf4fef4ef"

I have stored value of new checksum in a variable v = "4dfv45ffdf"

I want to replace the value after md5: from 32fdf4fef4ef to 4dfv45ffdf after replace above line in the file should like

"iso_checksum": "md5:4dfv45ffdf"

32fdf4fef4ef is not fixed value so we can not just replace like below

sed -i 's/32fdf4fef4ef/4dfv45ffdf/' file

4dfv45ffdf this is also not fixed value so kept in as $v

Can any please help me to perform the above task

CodePudding user response:

I would use GNU AWK for this task following way

awk -v v="4dfv45ffdf" '{gsub("md5:[[:xdigit:]] ","md5:"v);print}' file.json

Explanation: replace every md5: followed by 1 or more base16-digits using md5: concatenated with value of v, print whole line.

CodePudding user response:

Correct answer as below

y="4dfv45ffdf"

sed "/"iso_checksum":/s/(^[^:][:][ ]).$/\1"md5:$y",/" file.json

  • Related