RSS

[sed] Delete the lines lying in between two patterns

09 Jan

Let’s take an plain text file, input.txt, that looks like this

PATTERN-1
First line of unimportant text
Second line of unimportant text
PATTERN-2
Some more texts (may/ mayn't be important!)

We want to delete some of the lines from the file using the command line stream editor, sed.

1. Use the following command to delete the lines lying between PATTERN-1 and PATTERN-2 , excluding the lines containing these patterns:
sed '/PATTERN-1/,/PATTERN-2/{//!d}' input.txt

If you want to modify the file itself, instead of just the file stream, include the “-i” flag after sed.

2. Use the following command to delete the lines lying between PATTERN-1 and PATTERN-2 , including the lines containing these patterns:
sed '/PATTERN-1/,/PATTERN-2/d' input.txt

3. To delete all the lines after PATTERN-2, use this
sed '/PATTERN-1/,$d' input.txt

4. To delete lines, say 2 through 4 (if you know the correct line numbers, of course!), use this

sed '2,4d' input.txt

Here is a good sed reference.

About these ads
 
1 Comment

Posted by on January 9, 2013 in sed

 

Tags: , , , , , , , ,

One response to “[sed] Delete the lines lying in between two patterns

  1. skimeer

    August 20, 2014 at 5:42 AM

    Good Article

     

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

 
Follow

Get every new post delivered to your Inbox.

Join 34 other followers

%d bloggers like this: