且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用grep和sed将一个字符串替换为另一个字符串

更新时间:2022-11-16 15:35:58

Provided you have a sed which supports the -i option,

sed -i 's/version: .*/version: 1.2.3/' file1 file2 file3 ...

You may want to tweak the regex wildcard; .* matches through the end of the line, whereas [.0-9]* matches the longest possible sequence of dots and digits. You might also want to permit for variations in surrounding whitespace ... But since this is probably among the top 10% FAQs on this site, go look for similar questions at this point.

To obtain the replacement string from file1 and apply it to file2, file3, etc, something like

new=$(sed -n 's/version: //p' file1)
# Use double quotes, not single, in order to expand $new
sed -i "s/version: [.0-9]*/version: $new/" file2 file3 ...

The first sed invocation will only print lines on which "version: " was found and removed (replaced with an empty string). Presumably there will only be one such line in the file. Pipe the output to head -n 1 or uniq or something, or find / create a more elaborate sed script.

You normally use single quotes around literal strings, but since you don't want a literal $new in the replacement, we use double quotes, which allow the shell to perform variable replacement (and a number of other substitutions we don't go into here) in the quoted string.

相关阅读

技术问答最新文章