Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vi multiple command in one line

Tags:

vim

vi

I want to achieve the following things in vi :

  • Remove first few columns
  • Remove lines starting with specific words
  • Remove everything after first word.

I have the following command with respect to above requirements

:%s/new page //g to remove first two columns.
:g/abc/d , :g/xyz/d , :g/ddd/d to remove lines starting with specific words.
:%s/ .*//g to remove everything after first word.

Overall I want to run the following commands :

:%s/new page //g
:g/abc/d
:g/xyz/d
:g/ddd/d
:%s/ .*//g

How can I execute all the above commands in one single command.

I have tried | but it did not worked.

:g/abc/d|:g/xyz/d|:g/ddd/d

I am getting the following error :

E147: Cannot do :global recursive

How can I achieve this. I want to execute all commands in one single command.

Thanks

like image 879
Shivkumar Mallesappa Avatar asked Sep 06 '25 22:09

Shivkumar Mallesappa


2 Answers

You can put all those commands in a function:

function! AllMyCommands()
    %s/new  page   //g
    g/abc/d
    g/xyz/d
    g/ddd/d
    %s/ .*//g
endfunction

and call it either directly:

:call AllMyCommands()

or via a custom command:

command! Foo call AllMyCommands()
:Foo

or via a custom mapping:

nnoremap <key> :<C-u>call AllMyCommands()<CR>
<key>
like image 165
romainl Avatar answered Sep 09 '25 21:09

romainl


I have tried | but it did not worked.

:g/abc/d|:g/xyz/d|:g/ddd/d

In general, commands can be executed sequentially, separated by |, but there are exceptions, as :help :bar tells:

These commands see the '|' as their argument, and can therefore not be
followed by another Vim command:
[...]
:global
[...]

As a workaround, you can wrap them in :execute:

:exe 'g/abc/d'|exe 'g/xyz/d'|g/ddd/d

But putting them into a :function, as per @romainl's answer, is probably better.

like image 39
Ingo Karkat Avatar answered Sep 09 '25 20:09

Ingo Karkat