如何从ssh配置文件中删除主机条目?

时间:2016-03-20 06:22:03

标签: ssh sed

该文件的标准格式为:

Host example
  HostName example.com
  Port 2222
Host example2
  Hostname two.example.com

Host three.example.com
  Port 4444

知道主持人的短名称,我想删除整个条目,以便重新添加新的详细信息。

我最接近的是这个,除了我需要保留以下主机声明,第二个搜索词将捕获两个术语(如HostName):

sed '/Host example/,/\nHost/d'

2 个答案:

答案 0 :(得分:5)

使用GNU sed:

host="example"
sed 's/^Host/\n&/' file | sed '/^Host '"$host"'$/,/^$/d;/^$/d'

输出:

Host example2
  Hostname two.example.com
Host three.example.com
  Port 4444
  

s/^Host/\n&/:在以" Host"

开头的每一行之前插入换行符      

/^Host '"$host"'$/,/^$/d:删除所有匹配" Host $ host"到下一个空行

     

/^$/d:清理:删除每一个空行

答案 1 :(得分:1)

我的最终解决方案(有点OSX定位)是这样的。它主要基于赛勒斯早先的回答。

sed < $SOURCE "/^$/d;s/Host /$NL&/" | sed '/^Host '"$HOST"'$/,/^$/d;' > $SOURCE

这对于没有缩进的HostName指令更具弹性。