Sed command to find the line containing a string and replacing part of it

Viewed 52

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.

3 Answers

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',

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
awk -v tag="'new_revision':" -v val="'000c0000b08b96c987482e08d28d84ea3d777eml'," '$1==tag{$2=val} 1' file
'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',
Related