Frank Cheng
Frank Cheng

Reputation: 6186

How to combine :vim and :s in vim

For example, i have a task to search all file under current directory where contains "foo" and then replace to "bar".
Now here is my current solution:
:vim /bar/ **/*
Use this to search all appearances of foo, and then replace it one by one to "bar"
:s/foo/bar/gc
Obviously it is not a good solution when replaces becomes large. So if there is a better solution to combine these two operations into one. But there is a precondition : Must give a hint before replacement just like what the c does in the second command. This is prevent replace some word that doesn't need to replace.

Upvotes: 0

Views: 118

Answers (2)

Samus_
Samus_

Reputation: 2993

the easiest would be:

vim $(egrep -l '/foo/' **/*) -c 'bufdo %s/foo/bar/g'

but this will fail if there's whitespace on the filenames, a more robust approach would be:

files=()
while IFS= read -rd '' filename; do
    files+=("$filename")
done < <(egrep -Zl '/foo/' **/*)
vim "${files[@]}" -c 'bufdo %s/foo/bar/g'

Upvotes: 0

kev
kev

Reputation: 161644

Open all files in vim:

$ vim *

Replace foo with bar

:argdo %s/foo/bar/ | update

Tutorial: http://vim.wikia.com/wiki/Search_and_replace_in_multiple_buffers

Upvotes: 3

Related Questions