Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a command within Vim from the command line

Tags:

vim

Is there a way to execute a Vim command on a file from the command line?

I know the opposite is true like this:

:!python % 

But what if I wanted to :retab a 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'd like to chain this sequence together to a single command somehow.

It would be something like this:

> vim myfile.c retab | wq 
like image 745
syvex Avatar asked Feb 20 '12 18:02

syvex


People also ask

How do I execute a command inside a Vim editor?

This can be possible using below steps : First Go to command mode in vi editor by pressing 'esc' key and then type “:“, followed by “!” and the command, example is shown below. Example : Run the ifconfig command within the /etc/hosts file.

How do you run Unix commands while in a Vim session?

Go to command mode Esc , then run :! unix_command . Anything run from the : prompt starting with a bang ! will be run as a unix shell command. You'll be shown the output and allowed to hit a key to get back to your work in vim.

How do I find the command line in Vim?

You can also open the Vim : command line by pressing Ctrl-W : . The other Ctrl-W commands work as normal, so managing windows works the same no matter what type of window is currently selected.


1 Answers

This works:

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

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

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

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

like image 162
Firstrock Avatar answered Sep 21 '22 23:09

Firstrock