Sometimes, you are working with text files in Linux. And you have to remove the specific text string from any text file. Linux provides some commands for this like grep, sed, and awk commands. which is used to delete specific text from text files in linux. In this tutorial, you will learn how to delete lines in a text file that contain a specific string using grep, sed, and awk commands in Linux.
How to Delete Lines in a Text File That Contain a Specific String in Linux Ubuntu
By using the following ways, you can delete/remove lines in the text files that contain a specific string in Linux without opening:
- Method 1: Using the Sed Command
- Method 2: Using the Grep and VIM Commands
- Method 3: Using the AWK Command
Method 1: Using the Sed Command
First of all, open your terminal by pressing Ctrl + Alt + T key. And after that, you need to execute the Sed command to delete lines in a text file that contain a specific string:
sed -i '/string_to_delete/d' filename.txt
Here’s a breakdown of the above given sed
command:
-i
option is used to edit the file in place, which means that the file will be modified bysed
.'/string_to_delete/d'
is ased
command that tellssed
to search for the patternstring_to_delete
in the file and delete it. The/
character is used to enclose the pattern, and thed
command is used to delete it.filename.txt
is the name of the file to modify.
Method 2: Using the Grep and VIM Commands
Another method for deleting lines in a text file that contain a specific string is to use the Grep and VIM commands together.
So, open terminal or command line and execute Grep command in it to search and delete lines containing specific string:
grep -n "string_to_delete" filename.txt
In this command, replace the word “string_to_delete” with the word you want to delete from the file. And also replace filename.txt with your original file name.
Method 3: Using the AWK Command
Last and final method, which is awk command. So, execute the following AWK command on terminal or command line to delete lines in a text file that contain a specific string:
awk '!/string_to_delete/' filename.txt > tmpfile && mv tmpfile filename.txt
In this command, replace the word “string_to_delete” with the word you want to delete from the file. And also replace filename.txt with your original file name.
Note:- This command uses the ! operator to tell AWK to select all lines that do not contain the specified string. The output is then redirected to a temporary file (tmpfile) using the > operator. Finally, the temporary file is renamed to the original file using the mv command.
Conclusion
Deleting lines in a text file that contain a specific string is a common task in Linux. There are many ways to accomplish this task, including using the Sed, Grep and VIM, and AWK commands.
Choose the method that works best for your specific situation and use it to streamline your workflow and improve your productivity.