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
Provided you have a
sedwhich supports the-ioption,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
The first
sedinvocation 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 tohead -n 1oruniqor something, or find / create a more elaboratesedscript.You normally use single quotes around literal strings, but since you don’t want a literal
$newin 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.