Home > vim > vim – Delete lines that do not match a pattern.

vim – Delete lines that do not match a pattern.

Problem:
I wanted to move some python code from the interactive console to a python file. I needed to remove the >>> and … as well as the output lines.

>>> l1 = [2,2,3,4,5,2]
>>> l1.count(2)
3
>>> l1.count()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: count() takes exactly one argument (0 given)
>>> l1 = [2,2,3,4,5,2]
>>> if 3 in l1: 
...     print "yes"
... 
yes
>>> if 3 not in l1: 
...     print "no"
... 
>>> if 1 not in l1: 
...     print "no"
... 
no
>>> l1
[2, 2, 3, 4, 5, 2]
>>> 

Solution:

From http://vim.wikia.com

The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.

What I ended up using was

:g!/^\([>>>]\|[\.\.\.]\)/d

Which means delete lines that do not start with either >>> or … (Delete lines that do not match the pattern).

To produce

>>> l1 = [2,2,3,4,5,2]
>>> l1.count(2)
>>> l1.count()
>>> l1 = [2,2,3,4,5,2]
>>> if 3 in l1:
...     print "yes" 
...     
>>> if 3 not in l1:
...     print "no"
...     
>>> if 1 not in l1:
...     print "no"
... 
>>> l1 
>>> 

The rest was simple.

:%s/\(>>>\|\.\.\.\) //

Final Result

l1 = [2,2,3,4,5,2]
l1.count(2)
l1.count()
l1 = [2,2,3,4,5,2]
if 3 in l1: 
    print "yes"

if 3 not in l1: 
    print "no"

if 1 not in l1: 
    print "no"

l1

Source:
http://vim.wikia.com/wiki/Delete_all_lines_containing_a_pattern

NB:

:g/^\([>>>]\|[\.\.\.]\)/d

Means delete lines that match the pattern. (Lines that start with >>> or …).

Advertisements
Categories: vim Tags:
  1. June 7, 2012 at 12:48 pm

    Reading this post just brouht to my mind another article I’ve read in stackoverflow, with a very good explanation of vi tricks and history – there it was mentioned the origin of the “grep” ( /g/re/p” ) command, which actually comes from very near of what you showed here. – yours would be called “g/re/d” 🙂

    http://stackoverflow.com/questions/74625/what-is-the-best-way-to-force-yourself-to-master-vi

    PD: after reading both articles, it seems that “g!/…” is the same as “v/…”

    • June 7, 2012 at 1:34 pm

      Thanks for the stackoverflow link.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: