Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given a typical known_hosts file:

[]:22 ssh-rsa bbuivvhbkbjdnflksndkfnksnfk...
[]:14444 ssh-rsa hohdibsodbfoasbfbsabdfbsd...
[]: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
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

-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

You can use Vim in Ex mode:

ex -sc 'g/98\.76\.54\.32/d' -cx known_hosts
  1. g global search

  2. d delete

  3. x save and close

share|improve this answer

Your Answer


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.