sed 删除主机 IP 地址之前的所有内容

sed 删除主机 IP 地址之前的所有内容

我希望删除本地主机的 IP 地址之前的每一行。我通过以下方式成功查询主机的 IP 地址:

grep `hostname` /etc/hosts | awk '{print $1}'

现在我正在寻找如何通过 sed 实现这一点。示例(不起作用):

cat file | sed '/echo `grep `hostname` /etc/hosts | awk '{print $1}'`/,$!d'

如何将我的命令包含到 sed 中?

答案1

你要

 sed -n "/$(hostname)/,\$ p" /etc/hosts

答案2

根据您的 awk 示例,我认为您想要的解决方案是:

sed -ne "s/[[:blank:]]*$(hostname)$//p" /etc/hosts

$ hostname
foo.example.com
$ grep $(hostname) /etc/hosts
10.16.161.131         foo.example.com
$ sed -ne "s/[[:blank:]]*$(hostname)$//p" /etc/hosts
10.16.161.131

grep顺便说一句,每当您编写涉及通过管道传输到的命令列表时awk,它们通常可以组合起来:

$ awk "/$(hostname)/"'{print $1}' /etc/hosts
10.16.161.131

相关内容