Home > Software design >  Sed command to find the line containing a string and replacing part of it
Sed command to find the line containing a string and replacing part of it

Time:09-21

I have a file, which should have an entry like this -

'new_revision': '111c1110b08b96c987482e08d28d84ea3d777egh',

I want to find this line and replace it with something like this

'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',

I tried commands like-

sed -i 's/'new_revision': ''([a-z0-9]{40})''/'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml'/' file

But doesn't work properly and gives error as no matches found.

CodePudding user response:

You could use -E and wrap the sed command in double quotes and use the capture group in the first part, using a backreference \1 in the replacement.

sed -E s/"('new_revision': ')[a-z0-9]{40}'/\1000c0000b08b96c987482e08d28d84ea3d777eml'/" file

Output

'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',

CodePudding user response:

You don't want to do the search and replace on every line, you only want to do it on the lines that match. In other words, you should restrict the lines on which the s command is run with an address. eg:

$ new_hash=000c0000b08b96c987482e08d28d84ea3d777eml
$ sed "/^'new_revision':/s/'[^']*',$/'$new_hash'/" input

CodePudding user response:

awk -v t="'new_revision':" -v v="'000c0000b08b96c987482e08d28d84ea3d777eml'," '$1==t{$2=v} 1' file
'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',
  • Related