Let's say I have a function, named StripWhitespace
.
I can run it on a single file by opening the file and running :StripWhitespace
.
How can I automatically run that function against a folder of files, and save the results as I go along?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityLet's say I have a function, named StripWhitespace
.
I can run it on a single file by opening the file and running :StripWhitespace
.
How can I automatically run that function against a folder of files, and save the results as I go along?
You can use the -c
argument to run a command on startup, from vim(1)
:
-c {command}
{command} will be executed after the first file has been
read. {command} is interpreted as an Ex command. If the
{command} contains spaces it must be enclosed in double
quotes (this depends on the shell that is used). Example:
Vim "+set si" main.c
Note: You can use up to 10 "+" or "-c" commands.
Example:
vim -c ':call StripWhitespace()' file1 file2
To quit afterwards, add | :wqa
:
vim -c ':call StripWhitespace() | :wqa' file1 file2
If you are already in Vim, you can use the :argdo
or :bufdo
commands to execute a command on every item in the argument list or buffer list, respectively.
e.g. to run a :
command on every file in the argument list:
:argdo StripWhitespace
Or to invoke a function from every file in the buffer list:
:bufdo call StripWhitespace()
Or to run macro q
on every file in the arguments list:
:argdo normal @q
You can then save all changed buffers with :wall
, or save all and quit Vim with :wqall
.
If you want to write the files as you go along, you can add in a call to :update
, like so:
:argdo s/foo/bar/ge | update
There are various ways you can get the files into Vim in the first place, including:
vim *
(this adds all the files to the argument list),:args
command (which supports wildcards and backtick expressions) to populate the argument list, or the :argadd
command to add files to it,:e
, :Ex
, or a file-opening plugin.'hidden'
to be set; (2) the : update
command is a slight improvement over :w
because it only writes if a change has been made, so :bufdo update
or :argdo update
will write all modified buffers or arguments.
– tommcdo
Feb 12 '15 at 11:10
update
. I considered mentioning hidden
when I was writing the answer, but decided against it because I didn't want to overcomplicate it. On reflection though, it should be in there. I'll update the answer to include both suggestions presently.
– Rich
Feb 12 '15 at 11:18
:wall
, which also has the advantage of not cycling through buffers and moving you away from where you started. I suppose :argdo update
is still a different story -- maybe you don't want to write to buffers that are not in your argument list.
– tommcdo
Feb 12 '15 at 11:44