I have a set of multiple files requiring the same set of edits, I am trying to create a bash script for editing them in vi, however I don't know how to use vi within the scripts to make the edits? Any suggestions would be helpful.
-
3Instead of `vi` you can use `sed`. You can use `sed` inside the scripts. – sat Jan 18 '14 at 07:40
-
can you specify what's your `same set of edits`? – ray Jan 18 '14 at 07:41
-
I am sorry I should rephrase, I want to apply a recorded set of sequential commands(using qq) on around 100 files – Stephen Jacob Jan 18 '14 at 07:43
-
@sat Thank you for the sed suggestion, I'll be using that. Though I wonder if vi could be used. – Stephen Jacob Jan 18 '14 at 07:52
2 Answers
I'd highly recommend using sed
or awk
, both programs use regular expressions for selecting and processing text.
But here's how you can do it using vim too:
Vim has an ex
mode (aka commandline version) which solves this purpose and is much easier to use in scripts. Taking the solution from this answer:
You could simply include the following in your bashscript:
ex $yourfile <<EOEX
:%s/$string_to_replace/$string_to_replace_it_with/g
:x
EOEX
For example:
ex file.txt << EOEX
:%s/hello/world/g
:x
EOEX
Or you can use the -c
option to pass ex
commands to vim.
For example:
vim file.txt -c ':%s/hello/world/g' -c 'wq'

- 1
- 1

- 572
- 6
- 12
If you want to do a single :s
command, then you may we well use sed, or you can use vim -c
as @fnatic_shank suggests. For more complex scripts, you can use -S script.vim
instead of several -c
arguments. I like to use
$ vim -e -s -N -V0vim.log -S script.vim infile.txt
See the help for -N
, -V
, -S
, and especially
:help -s-ex
which includes the warning
If Vim appears to be stuck try typing "qa!". You don't get a prompt thus you can't see Vim is waiting for you to type something.
(I ran into this while testing my answer. I kept infile.txt open in vim, so it asked what to do about the existing swap file when I tried to start a new vim as above.) If you want to send the file to stdout, then you might have these two lines at the end of script.vim:
g/^
silent q!

- 5,054
- 16
- 18