deleting texts between patterns

Tim Chase python.list at tim.thechases.com
Fri May 12 08:29:54 EDT 2006


> I wish to delete lines that are in between 'abc' and
> 'xyz' and print the rest of the lines. Which is the best
> way to do it?

While this *is* the python list, you don't specify whether
this is the end goal, or whether it's part of a larger
program. If it *is* the end goal (namely, you just want the
filtered output someplace), and you're not adverse to using
other tools, you can do something like

	sed -n -e'1,/abc/p' -e'/xyz/,$p' file.txt

which is pretty straight-forward.  It translates to

-n       don't print each line by default
-e       execute the following item
1,/abc/  from line 1, through the line where you match "abc"
p        print each line
          and also
-e       execute the following item
/xyz/,$  from the line matching "abc" through the last line
p        print each line


It assumes that
1) there's only one /abc/ & /xyz/ in the file (otherwise, it
defaults to the first one it finds in each case)
2) that they're in that order (otherwise, you'll get 2x each
line, rather than 0x each line)

However, it's a oneliner here, and seems to be a bit more
complex in python, so if you don't need to integrate the
results into further down-stream python processing, this
might be a nice way to go.  If you need the python, others
on the list have offered a panoply of good answers already.

-tkc









More information about the Python-list mailing list