[英]Replace IP address figures with 'X' letters using sed (preserve character number)
I have a string containing several IPs. 我有一个包含多个IP的字符串。 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
. 我需要使用sed将所有IP中的所有数字替换为字母“ X”,即
10.135.1.03
将变为XX.XXX.X.XX
UPDATE String contains not only IPs, but other characters too: both letters and figures. UPDATE字符串不仅包含IP,而且还包含其他字符:字母和数字。 Need to replace only IP's figures.
只需要替换IP的数字即可。 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".
类似于“从192.168.1.1接收到5个连接,从10.0.0.1接收到26个连接,总共31个-2012年9月20日,星期二。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: 不确定为什么要使用
sed
btw, tr
语法稍微简洁一些:
out=$(tr [:digit:] X <<< "$str")
when using bash, even cleaner: 使用bash时,甚至更清洁:
out=${str//[0-9]/X}
Personally, I would find this very difficult with sed
. 我个人认为
sed
很难做到。 I think this would be much easier with GNU awk
: 我认为使用
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): 这可能对您有用(GNU sed,tr和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.