I have a file that contains a bunch of ip addresses. I would like for my sed command to remove the first two octets of these. ex. 172.0.0.1
should be changed to XXX.ZZZ.0.1
What I have now remove the lasts octets and replace it with an x!
sed -i 's/\\(\\([0-9]\\{1,3\\}\\.\\)\\{3\\}\\)[0-9]\\{1,3\\}/\\1XXX/g' "${file}"
This is run in a bash scripts that takes the file containing the ip addresses as input param.
I haven't been able to figure out how to do this with sed yet so I'll appreciate any help.
It seems you may use
sed -i.bak -E 's/\b([0-9]{1,3}\.){2}([0-9]{1,3}\.[0-9]{1,3})\b/XXX.ZZZ.\2/g' "${file}"
The -E
(or -r
on other OSes) enables the POSIX ERE syntax that allows using fewer escapes in the pattern (no need to escape grouping (
and )
symbols and the limiting/range quantifier {n,m}
).
Details
\\b
- word boundary ([0-9]{1,3}\\.){2}
- two occurences of (Group 1) one to three digits and a dot ([0-9]{1,3}\\.[0-9]{1,3})
- (Group 2) one to three digits, a .
and again 1 to 3 digits \\b
- word boundary The whole match is replaced with Group 2 value ( \\2
). The -i.bak
will make the replacements in file, and an original copy with a .bak extension will be generated.
See the online demo .
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.