1

I have a file which contains many id adress (Both IPV4 and IPV6). I want to use sed command to replace all the occurances of the old IP to new IP. But i am facing a problem ex:

old IPs like below

2.2.2.2             -IPV4      
2:2:2.2.2.2         - IPV6: Note ':'

In ksh, I am using

oldIP=2.2.2.2
newIP=3.3.3.3

sed -i 's/'$oldIP'/'$newIP'/g' filename.

But this is replacing both 2.2.2.2 and 2:2:2.2.2.2 because '.' in oldIP variable is used as regular expression.

Can any one tell how to match exact IP of a file in a scipt?

Input file: a.txt - contains oldIP,newIP

1.1.1.1,9.9.9.9
0.0.0.0,9.9.9.9
2.2.2.2,9.9.9.9
5:5:5.5.5.5,[9:9:9.9.9.9]
3.3.3.3,9.9.9.9
3:3:3.3.3.3,9:9:9.9.9.9
1:1:3.3.3.3,9:9:9.9.9.9

#!/bin/ksh

ipAddrFile=$1
while read line
do
    OLDIFS=$IFS
    IFS=","
    array=( $line )
    IFS=$OLDIFS

    if [ "${array[1]}" = "" ]; then
        echo "tokenize ip address list fail. Check if proper separator is used."
    fi

    oldIP=${array[0]}
    newIP=${array[1]}

    `sed -i 's/'$oldIP'/'$newIP'/g' temp.xml`
       if [ $? -ne 0 ]; then
       echo "Replacing field value failed"
      exit 1
   fi


done < $ipAddrFile
4

1 回答 1

3

首先 dot 需要在正则表达式中转义,否则它匹配任何字符。所以像这样设置你的变量:

oldIP="2\.2\.2\.2"
newIP="3.3.3.3"

然后你可以使用这个 sed:

sed -r "s/(^|[^:])$oldIP([^0-9]|$)/\1$newIP\2/g" input

或在 Mac 上:

sed -E "s/(^|[^:])$oldIP([^0-9]|$)/\1$newIP\2/g" input
于 2013-09-20T10:51:01.487 回答