Delete a Line from a File by Its Line Number

I keep having this problem. You know how ssh will tell you when the host’s keys have changed? For example, you try to ssh to

$ ssh

and you get

Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
Please contact your system administrator.
Add correct host key in /home/me/.ssh/known_hosts to get rid of this message.
Offending key in /home/me/.ssh/known_hosts:16
RSA host key for has changed and you have requested strict checking.
Host key verification failed.

Well, you can

$ ssh-keygen -R

But that doesn’t fix it completely. Try to connect again, and you may get something like

Warning: the ECDSA host key for '' differs from the key for the IP address ''
Offending key for IP in /home/me/.ssh/known_hosts:17
Matching host key in /home/me/.ssh/known_hosts:19
Are you sure you want to continue connecting (yes/no)?

Dammit! I used to open this in a text editor and delete the offending line. But let’s think about this. It gives us the line number, and it’s a Unix system. Can’t we automate this?

Yep. Use sed. The offending line is 17? All we have to do is

$ sed -i 17d ~/.ssh/known_hosts

So sed edits the file in-line (-i), and deletes the 17th line (17d). Hooray!

This entry was posted in fixes and tagged , , , , , . Bookmark the permalink.

2 Responses to Delete a Line from a File by Its Line Number

  1. Alex says:

    Actually, the easier way is to do this: ssh-keygen -R


    • force says:

      Do you mean that supplying the IP address instead of the host or domain name fixes this? I will give that a try the next time it comes up. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>