简体   繁体   中英

Replace IP address figures with 'X' letters using sed (preserve character number)

I have a string containing several IPs. I need to replace all of the figures in all the IPs with the letter 'X' using sed, ie 10.135.1.03 will become XX.XXX.X.XX .

UPDATE String contains not only IPs, but other characters too: both letters and figures. Need to replace only IP's figures. Something like "Received 5 connections from 192.168.1.1, 26 connections from 10.0.0.1, total 31 - Tuesday, 20.09.2012. MessageID: 212.132.15".

$ str="10.135.1.03"
$ echo $str | sed -e "s/[0-9]/X/g"
XX.XXX.X.XX

or in a scripting context, this is probably better:

out=$(sed -e "s/[0-9]/X/g" <<< "$str")

not sure why you wanted sed btw, tr has a slightly cleaner syntax:

out=$(tr [:digit:] X <<< "$str")

when using bash, even cleaner:

out=${str//[0-9]/X}

Personally, I would find this very difficult with sed . I think this would be much easier with GNU awk :

awk --re-interval '{ for (i=1; i<=NF; i++) if ($i ~ /([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}/) gsub(/[[:digit:]]/, "X", $i) }1' file.txt

Results:

Received 5 connections from XXX.XXX.X.X, 26 connections from XX.X.X.X, total 31 - Tuesday, 20.09.2012. MessageID: 212.132.15

This might work for you (GNU sed, tr and Bash):

sed -r 's/\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>/$(tr [0-9] X <<<&)/g;s/.*/echo &/e' file

you could cheat and do:

sed -r 's/\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>/X.X.X.X/g' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM