shel脚本编辑hosts文件(awk、sed、ed)

来源:互联网 发布:中国国民党知乎 编辑:程序博客网 时间:2024/06/06 02:15

1. ed命令写hosts、删除指定的hosts配置

echo --------------------------修改hosts文件 ,在末尾追加一行, /etc/hosts--------------------------
(echo 'a';echo '127.0.0.1 https://www.baidu.com ';echo '.';echo 'wq')|ed /etc/hosts  


echo --------------------------恢复hosts文件 ,删除指定行的配置, /etc/hosts--------------------------
(echo 'd';echo '127.0.0.1 https://www.baidu.com';echo '.';echo 'wq')|ed /etc/hosts  

2. awk分割字符串,循环,写文件

#!/bin/sh
echo -------------------------- awk  insert file --------------------------
x=‘10.35.45.84  mobile-api2011.baidu.com;127.0.0.1 elp.baidu.com;192.168.231.99 minder.baidu.com;’
#echo $x | awk '{ split($0,arr,";");for( i in arr) {print arr[i] >> "/etc/hosts"}}'


3.shell脚本 + sed分割字符串,循环,写文件

1)循环写文件

        echo $hosts        hosts=${hosts//,/ };        i=1        while((1==1))        do        split=`echo $hosts|cut -d ";" -f$i`        if [ "$split" != "" ]        then        ((i++))        sed -ie "/$split/d" /etc/hosts        echo $split >>/etc/hosts        else        break        fi        done        sed -ie '/^$/d' /etc/hosts        echo -------------------------- host file --------------------------        cat /etc/hosts        echo -------------------------- host file --------------------------or==================================================================================#!/bin/bashuser=$REMOTEi=1while((1==1))do        split=`echo $user|cut -d ";" -f$i`        if [ "$split" != "" ]        then                ((i++))                echo $split                sed -i "a $split" /etc/hosts        else                break        fidoneecho -------------------------- host file --------------------------cat /etc/hostsecho -------------------------- host file --------------------------

2)循环删除文件 /etc/hosts中 的匹配行的字符串

      <command>echo "-------------------------- clear host --------------------------"        echo $hosts        hosts=${hosts//,/ };        i=1        while((1==1))        do        split=`echo $hosts|cut -d ";" -f$i`        if [ "$split" != "" ]        then        ((i++))        sed -ie "/$split/d" /etc/hosts        else        break        fi        done        echo -------------------------- host file --------------------------        cat /etc/hosts        echo -------------------------- host file --------------------------
or===================================================================================

#!/bin/bash
user=‘10.35.45.84  mobile-api2011.baidu.com;127.0.0.1 elp.baidu.com;192.168.231.99 minder.baidu.com;’
i=1
while((1==1))
do
        split=`echo $user|cut -d ";" -f$i`
        if [ "$split" != "" ]
        then
                ((i++))
                echo $split
                sed -ie "/$split/d" /etc/hosts
        else
                break
        fi
done
echo -------------------------- host file --------------------------
cat /etc/hosts
echo -------------------------- host file --------------------------




阅读全文
1 0