Reputation: 43
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.
Upvotes: 4
Views: 1255
Reputation: 626747
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 boundaryThe 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.
Upvotes: 2