Run the command in Vim from the command line

Is there anyway the execution of the Vim command in a file from the command line?

I know the opposite is true:

:!python % 

But what if I wanted :retab to save the file without opening it in Vim? For example:

 > vim myfile.c :retab | wq 

This will open myfile.c, replace the tabs with spaces, and then save and close. I would like to somehow associate this sequence with one team.

It will be something like this:

 > vim myfile.c retab | wq 
+64
vim
Feb 20 '12 at 18:15
source share
3 answers

This worked for me:

gvim -c "set et|retab|wq" foo.txt

set et (= set expandtab ) ensures that the tab characters are replaced with the correct number of spaces (otherwise retab will not work).

I usually don't use it, but vim -c ... also works

+60
Feb 20 '12 at 18:25
source share

You have several options:

  • -c "commands" : Ex -c "commands" will be played when you enter them on the command line.
    In your example: vim myfile -c 'retab | wq' vim myfile -c 'retab | wq' . This is what First Croc suggested.

  • -S "vim source file" : will be the source specified by vim script
    (e.g. running vim -c "source 'vim source file'" ):

    If you have a script.vim file containing:

     retab wq 

    Then you can use vim myfile.c -s script.vim (extension doesn't matter much)

  • -s "scriptin file" : the contents of the file will be played, since it contains the usual mode commands: if you have a script.txt containing:

     :retab ZZ 

    with the end of lines consisting of a single ^M character (for example, you saved the script with :set fileformat=mac | w ), then you can run: vim myfile.c -S script.txt ( ZZ is another way to exit vim and save the current file).
    Note that you can write these scripts with vim my_file -W script.txt , but suffers from an error if you use gvim (GUI).

+56
Feb 20 '12 at 18:44
source share

This is not a direct answer to your question, but if you want to replace tabs with spaces (or do any other search / replace regular expressions) for a list of files, you can simply use the built-in search / replace sed:

 sed -i 's/\t/ /g' foo1.txt foo2.txt 

or

 ls *.txt | xargs sed -i 's/\t/ /g' 

(In this example, I replace each tab character with three spaces.)




NOTE: the -i flag means in-place operation.

On the sed man page:

  -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied) 
+2
Mar 25 '14 at 1:31
source share



All Articles