Question

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.

Était-ce utile?

La solution

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'

Autres conseils

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!
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top