Home » Unix command and scripts » sed delete line containing string

sed delete line containing string

Many times, we come across a situation where we need to delete lines from a file having the string. The General approach would be to open the file in the vi editor, search the string and then delete the line. This will be quite cumbersome if we have many occurrences and the file is big. It will become more tedious if we have to do it from multiple files. Here sed command comes in very handy. we can delete lines containing strings using sed easily.

Let’s first create a test file for an explanation

# cat test.html
<html>
<head>
<title>This is test</title>
<body>
This is test page
cat foo
foo the cat
zoo and cat
did I
</body>
</html>

sed delete line containing string

Suppose we have to delete all the lines containing the string cat

#sed -e '/cat/d' test.html
<html>
<head>
<title>This is test</title>
<body>
This is test page
did I
</body>
</html>

The above command does not change the file, you can use with -i to change the file

#sed -i -e  '/cat/d' test.html

Suppose you want to delete the line only if the string is present at the start of the line

#sed -e '/^cat/d' test.html

<html>
<head>
<title>This is test</title>
<body>
This is test page
foo the cat
zoo and cat
did I
</body>
</html>

sed delete line containing multiple matches

Suppose we have to delete all the lines containing the string cat or did

# sed -e '/cat/,/did/d' test.html
<html>
<head>
<title>This is test</title>
<body>
This is test page
</body>
</html>

sed delete all line except those containing string

Suppose we want to delete all the lines except those containing cat string

#sed -i '/cat/!d' test.html
# cat test.html
cat foo
foo the cat
zoo and cat

I hope you like this article on the sed delete line containing string

See also  What is shell and Shell Scripts

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top