Using just grep and sed, how do I replace all occurrences of:
a.example.com
with
b.example.com
within a text file under the /home/user/
directory tree recursively finding and replacing all occurrences in all files in sub-directories as well.
Try this command:
For me works the next command:
if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.
For example:
's@string/to/replace@new/string@g'
it is much simpler than that.
done
find i
=> will introduce all files in the folder and in subfolders to SED.sed -i
=> will replace in the files the relevant string if exists.The command below will search all the files recursively whose name matches the search pattern and will replace the string:
find /path/to/searchdir/ -name "serachpatter" -type f | xargs sed -i 's/stringone/StrIngTwo/g'
Also if you want to limit the depth of recursion you can put the limits as well:
find /path/to/searchdir/ -name "serachpatter" -type f -maxdepth 4 -mindepth 2 | xargs sed -i 's/stringone/StrIngTwo/g'
Try this:
grep -rl
will recursively search for theSEARCHSTRING
in the directories./
and will replace the strings usingsed
.Ex:
Replacing a name
TOM
withJERRY
using search string asSWATKATS
in directoryCARTOONNETWORK
This will replace
TOM
withJERRY
in all the files and subdirectories underCARTOONNETWORK
wherever it finds the stringSWATKATS
.I know this is a really old question, but...
@vehomzzz's answer uses
find
andxargs
when the questions says explicitlygrep
andsed
only.@EmployedRussian and @BrooksMoses tried to say it was a dup of
awk
andsed
, but it's not - again, the question explicitly saysgrep
andsed
only.So here is my solution, assuming you are using Bash as your shell:
If you are using a different shell, such as Unix SHell, let me know and I will try to find a syntax adjustment.
P.S.: Here's a one-liner:
Sources:
Bash: Iterating over lines in a variable
grep(1) - Linux man page
Official Grep Manual
sed(1) - Linux man page
Official sed Manual