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'