fbpx

Find String and Remove the Line which contains that String using shell

To search for a word and remove the entire line containing that word in the Bash shell, you can use the grep and sed commands together. grep is a command-line utility that searches for text patterns in input, while sed is a stream editor that can perform text transformations on input.

For example, to search for the word “foo” and remove any lines containing that word from a file named input.txt, you can use the following command:

				
					$ grep -v foo input.txt | sed '/^$/d'

				
			

This command will first use grep to search for lines in input.txt that do not contain the word “foo” (the -v option inverts the match). The output of grep will be piped to sed, which will remove any blank lines from the output using the /^$/d regular expression.

This command will not modify the original input.txt file. If you want to save the output to a new file, you can redirect the output to a file like this:

				
					$ grep -v foo input.txt | sed '/^$/d' > output.txt

				
			

This will save the output of the grep and sed commands to a new file named output.txt. You can then use this file as input for other commands or operations.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories