从文件中替换IP地址

时间:2017-03-21 08:01:01

标签: bash sed replace ip hostname

Sample.txt文件:

.........................
some log file entries
some log file entries
some log file entries
some log file entries
This system ip is not found
some log file entries
some log file entries
some log file entries
This system IP is 172.16.80.10
some log file entries
some log file entries
This system IP:172.16.80.10
some log file entries
some log file entries
some log file entries
Hostname::ip-172.16.80.10.ec2.internal
some log file entries
some log file entries
......................

我想从文件而不是主机名替换IP地址,但它也在更改主机名。

我正在使用此命令替换IP地址:

sed s/172.16.80.10/172.16.80.12/g  sample.txt

获得输出

.........................
some log file entries
some log file entries
some log file entries
some log file entries
This system ip is not found
some log file entries
some log file entries
some log file entries
This system IP is 172.16.80.12
some log file entries
some log file entries
This system IP:172.16.80.12
some log file entries
some log file entries
some log file entries
Hostname::ip-172.16.80.12.ec2.internal
some log file entries
some log file entries
......................

(也改变主机名)

所需的输出

.........................
some log file entries
some log file entries
some log file entries
some log file entries
This system ip is not found
some log file entries
some log file entries
some log file entries
This system IP is 172.16.80.12
some log file entries
some log file entries
This system IP:172.16.80.12
some log file entries
some log file entries
some log file entries
Hostname::ip-172.16.80.10.ec2.internal
some log file entries
some log file entries
......................

代码示例:

while getopts i:h: opt
  do
  case $opt in
  i)
    CurrentLocalIpv4=`curl -s http://169.254.169.254/latest/meta-data/local-ipv4`
    if [[ $OPTARG =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
      sed -i s/"$CurrentLocalIpv4"/"$OPTARG"/g /home/ec2-user/sample.txt
      echo "ip cahnged"
    else
      echo "fail"
    fi
    ;;
    h)
      echo"hostname"  ;;
   esac
 done

1 个答案:

答案 0 :(得分:2)

使用您的命令,您可以按如下方式修改它:

sed 's/172.16.80.10$/172.16.80.12/g' sample.txt

也就是说,告诉sed您只想更改要更改IP的行以及之后没有更多字符的行(172.16.80.10 $)。

如果您要在变量($ CurrentLocalIpv4)中修改IP,您可以按如下方式编写:

    sed 's/'$CurrentLocalIpv4'$/172.16.80.12/g' sample.txt