Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Given a typical known_hosts file:

[123.45.67.89]:22 ssh-rsa bbuivvhbkbjdnflksndkfnksnfk...
[98.76.54.32]:14444 ssh-rsa hohdibsodbfoasbfbsabdfbsd...
[77.34.122.33]:32209 ssh-rsa bksdjncknsdbcksbdcbhdhhb...

Not knowing the line# in the file, but knowing the ip address.


The following deletes all lines in the file:

sed '/98\.76\.54\.32/d known_hosts > known_hosts'

I'm hoping that I'm just missing something absurdly simple.

Testing my regex here gives me the match I need, and my impression is that:

sed '/pattern/d'  file > file

Should drop just the first line where the /pattern/ is a match.


I know I'm no regex guru nor bash master, but I seriously thought this was not going to be a several search, two coffee battle. Can anyone throw me a bone?


EDIT: 4 answers in minutes and all right. I knew it was something ridiculous. Hopefully my folly shows up in someone else's searching.

share|improve this question

5 Answers 5

up vote 1 down vote accepted

You have to use the -i option of sed (edit files in place):

sed -i '/98\.76\.54\.32/d' known_hosts

If you do an output redirection as you did you immediately empty the file (before its content is read by sed). If you want to use redirection you have to use a temporary output file:

sed '/98\.76\.54\.32/d' known_hosts > known_hosts.tmp
mv known_hosts.tmp known_hosts
share|improve this answer
    
First by seconds. Thank you... –  Cor Apr 19 '11 at 5:57

Unfortunately, redirecting your output onto your input file is working against you here, as the output gets opened for write and truncated before the shell actually launches sed. You'll need to write to a temporary file, or use the -i option of sed.

share|improve this answer

It's the > output redirection that is emptying the file. This is because the output file is opened before the input file. Use sed -i to do an in place edit

sed -i '/98\.76\.54\.32/d known_hosts
share|improve this answer

I sympathise, regex is not my friend. The > is overwriting the file. sed -i '/TO DELETE/ d' file.txt will do it.

share|improve this answer

Instead of sed, use ssh-keygen -R 98.76.54.32

-R hostname
Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts (see the -H option above)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.