Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

unix - Using grep and sed to replace one string with another

I'd like to replace one string from one file with a string from another file. Though I'm not experienced with these commands, I expect some combination of grep and sed would do it best.

What makes this a bit more complicated is that I don't know what either string is (I'm trying to automate replacing the version number on my documentation). I do know that in both cases the string I'm looking for (say "2.3.4") is preceded by "version:"

So can I say 'look for word (or rest of line or whatever is possible) after "version:" (let's call it string1) and do the same in another file (giving string2) and replace string string1 with string2.

Here are some example text files:

file1.txt

This is a file containing
the updated version number.
version: 2.3.4
here is a string with more info

file2.txt

This is a configuration file
It could contain an old version number
version: 2.3.2
Please update this

So the expected output for file2.txt would become:

file2.txt

This is a configuration file
It could contain an old version number
version: 2.3.4
Please update this

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...