Using Vim to replace all * non * matches with another string

When analyzing log files, I often use :g!/<string I want to keep in the log>/d to delete all lines from the log that do not contain the line of interest. Well, now I would like to use this powerful command to replace all strings that do not match the empty string.

I can not find enough information about :g! , except the one that I already use, and that format :g!/<match string>/<cmd> , where cmd is an "ex-command" or one of the commands: used in vim.

So I thought you could use the s command for this, but my understanding is limited in this area. Can anyone suggest how to format the command correctly? Or are there other tools more suitable for this task? (sed / awk? I actually never used them, but I know that they are quite powerful).

Another option is to simply punt and write a utility in Python to do this for me.

+7
vim regex replace search
source share
2 answers

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

Yes, you can use any ex command, including :s . By default :s acts on one 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/.*// 

- this is exactly what you want. You will probably want to follow :noh .

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

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

+12
source share

On Linux, you may prefer:

 :%!grep STRING_YOU_WANT_TO_KEEP 
0
source share

All Articles