Sed command to delete lines between two patterns

Share this post to your friends !
  • 1
    Share

Sed command to delete lines between two patterns
5 (100%) 1 vote[s]

WriteBash - How to use the sed command to delete lines between two patterns. In real situations, you will encounter many times to delete lines between two patterns. This article will guide you to use the sed command to do that job.

Situation required

I have the file mpm_prefork.conf, this is a configuration file of Apache2. Now, I want to delete all the lines in between the <Ifmodule> and </Ifmodule> tags. How to do it.

sed-command-to-delete-lines-between-two-patterns-01 Sed command to delete lines between two patterns
File mpm_prefork.conf of Apache2.

Delete lines between two patterns

The sed command structure to delete lines between two patterns (the command will not delete the two lines containing the pattern) that is:

sed -i '/pattern-1/,/pattern-2/{//!d}' filename

According to the above structure, I would write the command as follows:

sed -i '/<If/,/<\/If/{//!d}' mpm_prefork.conf
  • <If: this is the pattern-1.
  • <\/If: this is the pattern-2. Why is there an \ in front of /. We need to add \ to the sed command to talk that it is a character of the string to define.
  • {//!d}:  delete all lines between two patterns, exclude 2 lines contain patterns.

Check the result

1. I run the command to view the file contents.

cat mpm_prefork.conf

2. I run the command delete the line that I want.

3. Review the file content again.

sed-command-to-delete-lines-between-two-patterns-02 Sed command to delete lines between two patterns

In the image above, after running the sed command. You can see that the lines between the two tags we have defined have been removed.

If you liked this article, then please subscribe to our YouTube Channel for more video tutorials. You can also find us on Twitter and Facebook.


Share this post to your friends !
  • 1
    Share
If you appreciate what we share in this blog, you can support us by:
  1. Stay connected to: Facebook | Twitter | Google Plus | YouTube
  2. Subscribe email to recieve new posts from us: Sign up now.
  3. Start your own blog with SSD VPS - Free Let's Encrypt SSL ($2.5/month).
  4. Become a Supporter - Make a contribution via PayPal.
  5. Support us by purchasing Ribbon Lite Child theme being using on this website.

We are thankful for your support.

single post bottom banner
«« »»

Got something to say? Join the discussion

Please keep in mind that all comments are subject to our Comment Policy. Your email address will not be published.
This site uses Akismet to reduce spam. Learn how your comment data is processed.

One Comment