I need to use this command every once in awhile and I always forget how to do it off the top of my head.
grep -lr --exclude-dir=".git" -e "oldword" . | xargs sed -i '' -e 's/oldword/newword/g'
If you're on Windows you'll need unix command-line tools installed. The easiest way to do that is with Gow.
Here's what each piece does:
grepsearches for text in files recursively in a directory.
greptells it to only output file names when it finds a word match.
grepto search recursively in the directory, i.e. it will also look in subfolders if applicable.
--exclude-dir=".git"is optional; it tells
grepto ignore files in the
.gitdirectory. You can have more than one
--exclude-dirflag if you want to exclude multiple folders. Usually you won't want to look in the git folder though, if your folder is being tracked by git. Similarly, you can use the
--excludeflag to exclude files with certain patterns in their names, for example
--exclude="*\.min\.*"will exclude files with
.min.in their names. (You'll commonly want to exclude dependency folders like
grepsays that the following argument is a regular expression and can be omitted if you just want to type in a normal word or phrase.
"oldword"is the old word/expression you want to replace.
- The dot (
grepto look in the current directory. You can change that to a directory path, a specific file, or an asterisk (
*) if you want to search files in the current directory non-recursively.
- The pipe (
xargsto operate on the output of the
sedto use the output of
sed -imodifies text files. It takes an argument (the empty string
''in this case) which is a suffix for the output file; if the empty string is passed (as we are doing here) it will replace the input file.
sedto replace every instance of
newword. "s" means replace and "g" means every instance (as opposed to just the first one).
oldwordis a regular expression. You can omit
newwordif you just want to delete a word.
If you only want to operate on a single file and you already know which one it is, you can skip the
grepping and just use
sed. Wikipedia has a bunch of examples.