Search and replace over multiple files is difficult in my editor. There are plenty of tricks that can be done with find
, xargs
and sed
A UNIX way to do this with grep, xargs, and vi/vim:
This will help avoiding long commands when you want to exclude certain things from grep.
alias ge='grep --exclude=tags --exclude=TAGS --exclude-dir=.git --exclude-dir=build --exclude-dir=Build --exclude-dir=classes --exclude-dir=target--exclude-dir=Libraries --exclude=*.log --exclude=*~ --exclude=*.min.js -rOInE $*'
Command:
ge -l 'foo' .
Command:
ge -l 'foo' . | xargs -L 1 -o vim -c '%s/foo/bar/gc'
Explanation of the command:
The part till the pipe is the search command repeated
After the pipe, we call xargs to launch vim on each file
"-L 1" tells xargs to launch the command on each line instead of combining all lines in a single command. If you prefer to launch vim on all files at once, remove "-L 1" from xargs.
"-o" tells xargs to use the actual terminal rather than /dev/null
You have two options for this command:
a) Launch vim on all files at once
Advantages:
Disadvantages:
You have to switch to each buffer in turn and re-run the "%s" command on it
If you have a lot of files, this can make vim consume a lot of memory (sometimes as much as a full-blown IDE!)
b) Launch vim in turn for each file
Advantages:
Everything is automated. Vim is launched and performs the search command
Light on memory
Disadvantages:
I prefer variant b) as it's automated and more UNIX-like. With careful planification - inspecting the files list first, and maybe running the command on sub-directories to reduce scope - it is very nice to use.
General advantages:
It can be achieved with standard UNIX tools, available on virtually every platform
It's nice to use
General disadvantages:
You have to type the search expression twice
You might hit issues with bash escaping on complex search/replace expressions