Mudita Tandon
Mudita Tandon

Reputation: 1

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

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.

Upvotes: 0

Views: 74

Answers (3)

Ed Morton
Ed Morton

Reputation: 204558

awk -v tag="'new_revision':" -v val="'000c0000b08b96c987482e08d28d84ea3d777eml'," '$1==tag{$2=val} 1' file
'new_revision': '000c0000b08b96c987482e08d28d84ea3d777eml',

Upvotes: 1

William Pursell
William Pursell

Reputation: 212634

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

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163632

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

Upvotes: 1

Related Questions