Replace IP Address from file

假装没事ソ 提交于 2020-01-04 07:09:30

问题


Sample.txt file:

.........................
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
......................

I want to replace the IP Address from file not the host name, however it is changing hostname also.

I am using this command to replace IP address:

sed s/172.16.80.10/172.16.80.12/g  sample.txt

Getting Output

.........................
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
......................

(Changing Hostname also)

Desired output is

.........................
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
......................

Code example:

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:


Using your command, you can modify it as follows:

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

That is, telling sed that you want only change the lines with the IP to be changed and which have no more characters after it (172.16.80.10$).

In case of you have the IP to be modified within a variable, ($CurrentLocalIpv4), you may write it as follows:

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


来源:https://stackoverflow.com/questions/42921277/replace-ip-address-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!