[ACCEPTED]-Execute a command within Vim from the command line-vim

Accepted answer
Score: 66

This works:

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

set et (= set expandtab) ensures the tab characters 7 get replaced with the correct number of 6 spaces (otherwise, retab won't work).

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

The solution 4 as given above presumes the default tab 3 stop of eight is appropriate. If, say, a 2 tab stop of four is intended, use the command 1 sequence "set ts=4|set et|retab|wq".

Score: 58

You have several options:

  • -c "commands" : will play Ex 13 commands as you entered them in the command 12 line.
    In your example : vim myfile -c 'retab | wq'. This is what 11 Firstrock suggested.

  • -S "vim source file" : will source given 10 vim script
    (like running vim -c "source 'vim source file'"):

    If you have 9 a file script.vim containing:

    retab
    wq
    

    Then you can use vim myfile.c -s script.vim (the 8 extension does not really matter)

  • -s "scriptin file": will 7 play contents of file as it contains normal mode commands: If 6 you have script.txt containing:

    :retab
    ZZ
    

    with end of lines consisting of a single ^M character (for example you saved 5 the script using the :set fileformat=mac | w), then you can run: vim myfile.c -S script.txt (ZZ is 4 another way to exit vim and save current 3 file).
    Note that you can record those scripts 2 with vim my_file -W script.txt, but it suffers a bug if you happen to use gvim 1 (the GUI).

Score: 2

Not a direct answer to your question, but 7 if you want to replace tabs with spaces 6 (or do any other regex search/replace) for 5 a list of files, you can just use in-place 4 sed search/replace:

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

or

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

(In this example I 3 am replacing each tab character with three 2 spaces.)


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

From 1 the sed man page:

   -i[SUFFIX], --in-place[=SUFFIX]

          edit files in place (makes backup if  extension
          supplied)

More Related questions