![](/img/trans.png)
[英]Need to grep /etc/hosts with a known hostname, and then capture the ip address for the hostname from /etc/hosts
[英]1 Liner Script to get IP Address of server (ifconfig) and append to HostName to /etc/hosts for matching ipaddress
我有以下/ etc / hosts文件
[root@vhost41 tmp]# cat hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
119.13.248.1 ccvcds1.ihost.com vcds1
171.221.160.11 vhost.ihost.com vhost41
[root@vhost41 tmp]# echo $(ifconfig eth0 | grep "inet addr:" | cut -d ":" -f 2 | cut -d " " -f 1)
171.221.160.11
如何使用sed或awk一行將“ AWSHOST”添加到匹配的ip行。 因此更改將是:
[root@vhost41 tmp]# cat hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
119.13.248.1 ccvcds1.ihost.com vcds1
171.221.160.11 vhost.ihost.com vhost41 AWSHOST
我試圖通過管道將上述命令的輸出傳遞給sed和awk,但它不起作用。 任何幫助,不勝感激
您可以這樣使用sed
:
$ cat /etc/hosts
127.0.0.1 localhost
171.1.1.1 myhost
$ sudo sed -i 's/\(171\.1\.1\.1\).*/&\ mynewhost/g' /etc/hosts
$ cat /etc/hosts
127.0.0.1 localhost
171.1.1.1 myhost mynewhost
“& &
將被捕獲的表達式替換,例如此處171.1.1.1 myhost
,然后將其轉義后的空格和新的主機別名(此處為mynewhost
附加到它mynewhost
編輯
如David Ravetti所述,如果您不想在原地編輯文件,則可以添加要添加到備份文件的擴展名。
sed -i .bak ......
然后,將在適當位置編輯文件(用您的編輯替換),但是將使用.bak
擴展名備份原始文件。
sed -i "/$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | cut -d' ' -f1)[ \t]/ s/$/ AWHOST/ " hosts
嘗試這個
sed -i "s/\\(171.221.160.11\\) \\(.*\\)/\\1 \\2 MYHOST/g" temp.txt
這是awk
awk '{if ($1 == "171.221.160.11") {b=$1;for(i=1; i<=NF; ++i){$1="";a=a" "$i;}$0 =b" "a" ""MYHOST3" } print}' temp.txt > temp2.txt
我無法決定選擇sed
還是awk
,所以現在我總是兩者都做:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.