0

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.

user9517
  • 115,471
  • 20
  • 215
  • 297
Cor
  • 15
  • 1
  • 5

6 Answers6

2

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)

sciurus
  • 12,678
  • 2
  • 31
  • 49
1

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
bmk
  • 2,339
  • 2
  • 15
  • 10
1

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.

justarobert
  • 1,869
  • 13
  • 8
1

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
user9517
  • 115,471
  • 20
  • 215
  • 297
1

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

Jonathan Ross
  • 2,183
  • 11
  • 14
0

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

Zombo
  • 1
  • 1
  • 16
  • 20