Monday, July 21, 2008

Delete next few lines using sed


Title
____________

Delete next few lines where the pattern is found.

Input file
____________

$ cat para.txt
#Element1.blk
{
(Type= Fan)
(Name = KOL)
(Description = )
}
#Element2.blk
}
(Type= PPlug)
(Name = NIC)
(Description = )
}
#Element3.blk
}
(Type= Fan)
(Name = RIP)
(Description = )
}


Output required:
________________

If I search for "Element2.blk", the line containing "Element2.blk" and next 5 lines should be deleted.

#Element1.blk
{
(Type= Fan)
(Name = KOL)
(Description = )
}
#Element3.blk
}
(Type= Fan)
(Name = RIP)
(Description = )
}


sed solution
___________________________

$ sed '/#Element2.blk/{N;N;N;N;N;d;}' para.txt

7 comments:

SkyWalker said...

What if If I search for "Element2.blk", the lines after the "Element2.blk" line should be deleted. Noting but excluding the Element.blk line?

Jadu Saikia said...

@SkyWalker, do you mean this ?

$ sed '/#Element2.blk/{p;N;N;N;N;N;d;}' file.txt

Thanks.

SkyWalker said...

Hey!
Yes thanks.
Well I have a file named "test.txt" in which I have the contents as


test1
test2
test3
BEGIN
test4
test5
test6
END
test7
test8
test9
BEGIN
test10
test11
END
----


Now I want to have the file modified in such a way that what ever is there in between BEGIN and END should be deleted provided BEGIN statement should exist.

Like
test1
test2
test3
BEGIN
test7
test8
test9
BEGIN


Thanks

Jadu Saikia said...

@SkyWalker, I have this quick solution; but let me think if we can have a better one.

$ sed '/^BEGIN/,/^END/{//p;d;}' file.txt | sed '/^END/d'

o/p:

test1
test2
test3
BEGIN
test7
test8
test9
BEGIN

Jadu Saikia said...

I have put a python solution here http://pythonstarter.blogspot.com/2009/10/python-delete-lines-between-two-pattern.html

you can modify it.

SkyWalker said...

Hey Jadu! thanks a lot for your help
yes the code really helped me out.

Thanks

Tam Bakan said...

Very good site for sed and awk.

For this post, what modifications do i need if the START pattern is the same, and END has several patterns, and I just need to remove the lines in between?

START
test1
test2
test3
1st end pattern
line1
START
test4
test5
test6
2nd-end-pattert
line2
START
test7
test8
test9
3rd-end-pattern

Output:

START
1st end pattern
line1
START
2nd-end-pattern
line2
START
3rd-end-pattern

Thanks for the help.

© Jadu Saikia www.UNIXCL.com