Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change of ip address using perl or sed

I’ve an input file that consists of IP Address and subnet masks. As an example,

1.example.com,10.135.10.111,255.255.255.0,some comment
2.example.com,10.135.10.112,255.255.255.0,some comment
3.example.com,10.135.10.113,255.255.255.0,some comment
4.example.com,10.135.10.11,255.255.255.0, some comment
10.135.10.111 A 
10.135.10.112 A
10.135.10.113 A
10.135.10.11  A

I loop the IP address in my bash script and when using the perl or sed command all .11 gets changed. As an example:

inputip=10.135.10.11
newip=10.135.10.77

perl -i -e 's/$inputip/$newip/g' inputfile

OR

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed -e "s/$inputip/$newip/g" inputfile

The problem is all instance of .11 gets changed. so the above record of 10.135.10.111 is changed to 10.135.10.771, .772, .773, .77

Note: this line 10.135.10.11 A is not necessarily the last line, it’s anywhere in the file.

>Solution :

Input:

$ cat inputfile
1.example.com,10.135.10.111,255.255.255.0,some comment
2.example.com,10.135.10.112,255.255.255.0,some comment
3.example.com,10.135.10.113,255.255.255.0,some comment
4.example.com,10.135.10.11,255.255.255.0, some comment
4.example.com,210.135.10.11,255.255.255.0, some comment
10.135.10.111 A
10.135.10.112 A
10.135.10.113 A
10.135.10.11  A
210.135.10.11 A

With GNU sed and word boundary flags (\< / \>):

$ inputip=10.135.10.11
$ newip=10.135.10.77
$ sed "s/\<$inputip\>/$newip/g" inputfile
1.example.com,10.135.10.111,255.255.255.0,some comment
2.example.com,10.135.10.112,255.255.255.0,some comment
3.example.com,10.135.10.113,255.255.255.0,some comment
4.example.com,10.135.10.77,255.255.255.0, some comment
4.example.com,210.135.10.11,255.255.255.0, some comment
10.135.10.111 A
10.135.10.112 A
10.135.10.113 A
10.135.10.77  A
210.135.10.11 A

If this does not work then OP is likely not using GNU sed; in this case we’d need to know what version of sed is in use (eg, sed --version).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading