Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Vim to replace all *non* matching strings with another string

When parsing log files, I often use :g!/<string I want to keep in the log>/d to remove all lines from the log that don't contain a string of interest. Well, now I'd like to use this powerful command to replace all strings that don't match with an empty line.

I can find little to no information on :g!, other than the command that I already use, and that the format is :g!/<match string>/<cmd>, where cmd is an "ex command", or one of the : commands used in vim.

So I thought it might be possible to use the s command to do this, but my understanding is limited in this area. Can anyone suggest how to format the command properly? Or are there other tools better suited for this task? (sed / awk? I haven't really ever used those but know they are pretty powerful).

The other option is to just punt and write a utility in Python to do it for me.

like image 612
Dave Avatar asked Jan 13 '14 04:01

Dave


2 Answers

First of all, you can use :v as a shortcut for :g!. The etymology comes from the -v option to the standard grep command, I think.

Yes, you can use any ex command, including :s. By default, :s acts on a single line; combining it with :g (or :g! or :v) you can select the lines on which it acts. If I understand correctly, then

:v/<string I want to keep>/s/.*//

is exactly what you want. You will probably want to follow up with :noh.

Addendum: I am a little surprised at how popular this short answer has been. A funny thing is that the docs (:help :g and then scroll down a bit) mention :%s/pat/PAT/g as an alternative ("two characters shorter!") to :g/pat/s//PAT/g. I think this means that :g/pat/s/ used to be more familiar than :%s/pat/.

Shameless plug: for more on :g and :s, you might also be interested in my answer to why :%s/^$//g is not equal to :g/^$/d in vim?

like image 81
benjifisher Avatar answered Nov 12 '22 18:11

benjifisher


On linux you might prefer:

:%!grep STRING_YOU_WANT_TO_KEEP
like image 43
sjas Avatar answered Nov 12 '22 19:11

sjas