Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - find a keyword in a file and delete its line [duplicate]

I'd like to give a keyword, find the line where this keyword aṕpears in a file and erase the entire line.

This is what I got but it is not working as it should:

KEYWORD='domain.com'
cat /etc/hosts | grep -v "$KEYWORD" > /etc/hosts

UPDATE

This is what worked for me:

sed -i_bak -e '/domain\.com/d' /etc/hosts

However, as I had two lines with "domain.com", is there a way to tell sed to erase only the line where the exact keyword "domain.com" appears

This is the original content of /etc/hosts:

127.0.0.1       localhost       localhost.localdomain
222.111.22.222      hvn.domain.com
222.111.22.222      domain.com

Here's how it end up after the command sed -i_bak -e '/domain\.com/d' /etc/hosts:

127.0.0.1       localhost       localhost.localdomain

I tried sed -i_bak -e '/\<namourphoto\.com\.br\>/d' ~/Desktop/hosts but it didn't work.

CONCLUSION

This is the code I came up with (based on the help the fine folks have given me):

D=domain.com
DOMAIN=`echo "$D" | sed 's/\./\\\\./g'`
sed -i_bak -e "/[\t]$DOMAIN/d" /etc/hosts

Note that:

  • I am counting that there is always a tab before the domain to be erased

  • I am automatically escaping the dots of the domain name.

like image 931
Roger Avatar asked Aug 13 '11 13:08

Roger


People also ask

How do I remove duplicate lines in files?

Remove duplicate lines with uniq If you don't need to preserve the order of the lines in the file, using the sort and uniq commands will do what you need in a very straightforward way. The sort command sorts the lines in alphanumeric order. The uniq command ensures that sequential identical lines are reduced to one.

How do I find duplicate lines in a text file in Linux?

The uniq command in Linux is used to display identical lines in a text file. This command can be helpful if you want to remove duplicate words or strings from a text file. Since the uniq command matches adjacent lines for finding redundant copies, it only works with sorted text files.

How do I find duplicates in a text file?

To start your duplicate search, go to File -> Find Duplicates or click the Find Duplicates button on the main toolbar. The Find Duplicates dialog will open, as shown below. The Find Duplicates dialog is intuitive and easy to use. The first step is to specify which folders should be searched for duplicates.


1 Answers

Use the stream editor, sed:

sed -i ".bak" '/culpa/d' test.txt

The above will delete lines containing culpa in test.txt. It will create a backup of the original (named test.txt.bak) and will modify the original file in-place.

like image 105
miku Avatar answered Sep 29 '22 14:09

miku