Tuesday, October 6, 2009

Python - delete lines between two pattern


Input file:

$ cat input.txt
test1
test2
test3
BEGIN
test4
test5
test6
END
test7
test8
test9
BEGIN
test10
test11
END
test12

Required:
From the above file delete the lines which are between a BEGIN-END block and print rest of the lines.

The python script deleteline.py:

flag = 1
linelist = open("input.txt").readlines()
for line in linelist:
if line.startswith("BEGIN"):
flag = 0
if line.startswith("END"):
flag = 1
if flag and not line.startswith("END"):
print line,

Executing it:

$ python deleteline.py
test1
test2
test3
test7
test8
test9
test12

Now if we need to print the lines which are between a BEGIN-END block.
Here is a modification of the above scirpt.

flag = 1
linelist = open("input.txt").readlines()
for line in linelist:
if line.startswith("BEGIN"):
flag = 0
if line.startswith("END"):
flag = 1
if not flag and not line.startswith("BEGIN"):
print line,

Executing it:

$ python printline.py
test4
test5
test6
test10
test11

Related post:

- Lookup file operation using python

0 Comments: