How to delete lines containing a specific string in a text file in linux/unix

In the process of using linux/ unix, it is one of our most commonly used operations to find whether the specified string is included in the file.

Similarly, deleting the line containing the specified string in the text file is also one of the operations we often use. This article will share with you how to delete lines in a text file that contain specified strings.

There are multiple ways to delete the line containing the specified string in a text file: sed command, awk command and grep command.

Below we will share specific operation methods with you through examples.

The following text content is the content of our test file, we will use the following content as an example.

Hello everyone!
I share the linux tutorial with you at www.linuxcommands.site.
sed is a text processing command.
Awk is also a text processing command.
grep is also a text processing command.
They are our most commonly used tool set.
They are great.

Use the sed command to delete lines containing the specified string

In the following example, we will use the action option of the sed command to delete lines containing the specified string in the text file. As follows, we delete the line that contains the string “sed” in the file.

➜  ~ sed '/sed/d' text.txt

You can also use the sed -i ‘/sed/d’ text.txt to modify the contents of the file directly.

Explanation of sed options:
* -i extension
Edit files in-place, saving backups with the specified extension.
* action options: d
Delete the pattern space

Use the grep command to delete the line containing the specified string

Grep command, we use it more to match the specified string in the text file. Since it can be matched, it can also be excluded, you need to use the grep -v option.

In the following example, we use the grep command to delete the line containing the specified string. As follows, we delete the line that contains the string “grep” in the file.

➜  ~ grep -v "grep" text.txt

The result of grep -v, we just use “>” to redirect the result to a new file.

Explanation of grep options:
* -v, –invert-match
Selected lines are those not matching any of the specified patterns.

Use the awk command to delete the line containing the specified string

In the following example, we will use the awk command to delete the line containing the specified content in the text file.

➜  ~ awk '!/Awk/{print $0}' text.txt

Add a Comment

Your email address will not be published.