问题
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