简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM