Sed command to delete lines between two patterns

by Daniel Pham
Published: Updated:

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
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

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.

(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).

0 0 votes
Article Rating

You may also like

Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

DevOps Lite is a personal blog specializing in technology with main topics about DevOps, DevSecOps, SRE and System Administrator. Articles are shared for free and contributed to the community.

SUPPORT US

FOLLOW US

Subscribe my Newsletter for new blog posts. Stay updated from your inbox!

© 2021-2024 DevOpsLite.com – All rights reserved.

Please write sources “DevOpsLite.com” when using articles from this website.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

0
Would love your thoughts, please comment.x
()
x

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.