3

Assume you have some text file (e.g. a log file) and you open it in a vim editor and hit the command

:g/aaa

It will output a result in which you can move with j and k keys and when you move to the bottom a green sentence Press ENTER or type command to continue will appear.

I understand it somehow, that I can use some commands with the result, but don't know how to find what I can do with it.

One action I'd like to do, is to save the lines to the new file.

Of course you could use a command

$ grep aaa file.txt > new_file.txt

but is it possible from the vim editor directly?

10
+100

It is possible to do this through a multi-step process.

Within vim:

:redir > new_file.txt
:g/aaa
:redir END

See :help redir from within vim.

The :redir command can also append to an existing file by modifying the first command.

:redir >> new_file.txt
  • 1
    Or one could use :vimgrep and :grep with :copen. – JdeBP Jan 6 '17 at 8:05
1

The way I do it is to reverse the :g into :v and do :v/pattern/d, then copy the resulting text into a register with 1GVG"ry and finally undo the :v with u. Now the matched lines are safely in register r.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.