简体   繁体   English

Sed 命令查找包含字符串的行并替换其中的一部分

[英]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.您可以使用-E并将 sed 命令用双引号括起来,并在第一部分中使用捕获组,在替换中使用反向引用\1

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

Output 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.换句话说,您应该使用地址限制运行s命令的行。 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',

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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