Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove occurrences of string in text file

How would you remove a specific string from a text file (command line) e.g.

hello
goodbye
goodbye
hello
hello
hello
goodbye

In this case I would like to remove all occurrences of "goodbye"

Either linux or Windows, (as longs as the linux command is available in GNU)

like image 662
James Avatar asked May 13 '11 22:05

James


People also ask

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I remove a specific pattern from a Unix file?

Just like in VIM, we will be using the d command to delete specific pattern space with SED. To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command.


1 Answers

sed -i -e 's/goodbye//g' filename

To delete multiple words:

sed -i -e 's/\(goodbye\|hello\|test\|download\)//g' filename
like image 112
linuts Avatar answered Oct 02 '22 13:10

linuts