Search and replace in files named NAME
From Vim Tips Wiki
Tip 324 Previous Next created September 7, 2002 · complexity intermediate · author Luis Mondesi · version 5.7
I'm not sure if there is a simple way to do this from within Vim, but, I wrote this simple script that does it. It basically searches for files named NAMED (whatever name pass) for a given string and replaces that with a given string:
find_replace.sh NAMED "string_to_find" "string_to_replace"
This is all done from the command line without opening Vim.
Of course one could do things like:
let n = 1
while n <= argc() " loop over all files in arglist
exe "argument " . n
" start at the last char in the file and wrap for the
" first search to find match at start of file
normal G$
let flags = "w"
while search("foo", flags) > 0
s/foo/bar/g
let flags = "W"
endwhile
update " write the file if modified
let n = n + 1
endwhile
As suggested in the Vim help files, but, I wanted to go and find only these files. Here is the script:
#!/bin/sh
# Luis Mondesi
# Use Vim to replace a given string for
# another in a number of files.
#
# usage:
# find_replace.sh file "string" "replace"
#
if [ $1 -a $2 -a $3 ]; then
for i in `find . -name "$1" -type f | xargs grep -l $2`; do
# how do search and replace
# the screen might flicker... vim opening and closing...
vim -c ":%s/$2/$3/g" -c ":wq" $i
done
exit 0
fi
# I should never reach here
echo -e "USAGE: find_replace.sh file 'string' 'replace' \n\n"
exit 1
[edit] Comments
If you have a shell script environment available to you, you must also have sed. Why not just pipe the output of the find to xargs sed -e "%s/<from>/<to>/g"?
