2

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?

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • 1
    You want sed, not grep. Also, you're using "smart" quotes, so grep will search for the literal string “string”, including the quotes. You want "string" (or probably even better, 'string', unless you plan on using parameter expansion in the search term). – Benjamin W. Oct 01 '18 at 00:51
  • 1
    grep isn't used to replace strings. It's used for finding strings. To replace them, you need sed or awk. – Nasir Riley Oct 01 '18 at 00:52
  • So would it be something like – Cody Rutscher Oct 01 '18 at 00:54
  • sed --recursive --ignore-case "string", "replacement-string" – Cody Rutscher Oct 01 '18 at 00:54
  • Related: 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 to sed – steeldriver Oct 01 '18 at 00:58
  • Is there not a way to do it in one command where it searches for all instances and then replaces them? – Cody Rutscher Oct 01 '18 at 00:59
  • @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"; } then sed-ri 's/foo/bar/g' files and dirs ... –  Oct 01 '18 at 02:04
  • @Goro your edits are changing the meaning of the question again. – Chris Davies Oct 01 '18 at 20:24
  • @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! –  Oct 01 '18 at 20:27
  • 1
    @Goro I've already rolled back. Part of the problem, I think, is that you don't use the summary field to explain why you have made an edit. In this case if you had added a summary such as, "After long chat OP actually wants a different question; editing to new requirement" or something then it would have been more obvious that you were intentionally changing the meaning. – Chris Davies Oct 01 '18 at 20:31
  • @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 ;-) –  Oct 01 '18 at 20:35

1 Answers1

6

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' {} \;