Grep global find replace
6,187
Try this command
grep -rl "wavbyte" somedir/ | xargs sed -i 's/wavbyte/gitship/g'
You can try find
and sed
find /some_path -type f -exec sed -i 's/oldstring/newstring/g' {} \;
Related videos on Youtube
Author by
Cody Rutscher
Updated on September 18, 2022Comments
-
Cody Rutscher over 1 year
Is there a way to grep for a regular expression on an Ubuntu server and then find and replace it with another string? I am using the following command right now, but it doesn't account for actually changing the grepped string:
grep --recursive --ignore-case “string”
If I use awk or sed how would I write it to replace for instance "wavbyte" with "gitship" for all instances where "wavbyte" occurs for my entire server?
-
Cody Rutscher over 5 yearsSo would it be something like
-
Cody Rutscher over 5 yearssed --recursive --ignore-case "string", "replacement-string"
-
smw over 5 yearsRelated: search and replace using grep (not sed) - however you could use
grep --recursive --files-with-matches
to construct a list of file names to be passed tosed
-
Cody Rutscher over 5 yearsIs there not a way to do it in one command where it searches for all instances and then replaces them?
-
mosvy over 5 years@CodyRutscher you can do your own command by putting all that in a function or script:
sed-ri(){ e="$1"; shift; find "$@" -type f -print0 | xargs -0 sed -i "$e"; }
thensed-ri 's/foo/bar/g' files and dirs ...
-
roaima over 5 years@Goro your edits are changing the meaning of the question again.
-
Admin over 5 years@roaima Thank you so much! Actually, I was on a very long chat last night with the OP (link below) and his problem was completely not relevant at all to his question. Given that I solved his problem, I rewarded the question to reflect the problem. If this is not acceptable we can rollback. Apologies!
-
Admin over 5 years@roaima . Thank you for the note! You are completely correct! Indeed, I neglected adding summary about the objective of the changes.... I will definitely take this into account in the future! Your feedback is appreciated thanks ;-)
-
-
Cody Rutscher over 5 yearsDo I replace "matchstring" with the new or old string and what if I want to do it from the root directory of the server?
-
Cody Rutscher over 5 yearsFor instance if I am replacing "wavbyte" with "gitship" from the root directory of the Ubuntu server would it be:
-
Cody Rutscher over 5 yearsfind / -type f -exec sed -i 's/wavbyte/gitship/g' {} \;
-
Cody Rutscher over 5 yearsRight, but wavbyte is in a lot of different places in the server. How am I going to memorize all of those locations and then go in by hand and change to gitship?
-
Cody Rutscher over 5 yearsLet us continue this discussion in chat.