Vituvo
Vituvo

Reputation: 1048

How to use sed to replace all ips in a file if the first 3 octets match

Ubuntu 16.04 with GNU bash, version 4.4.0

I need to post my dmesg but before I do this, I want to remove all destination ips and replace them with xxx.xxx.xxx.xxx

The first 3 octets are the same but the last octet is different like so:

example: DST=123.12.12.145

sed -i 's/DST=123.12.12.???/DST=xxx.xxx.xxx.xxx/g' filename

Upvotes: 2

Views: 331

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

sed -i -E 's/DST=123\.12\.12\.[0-9]{1,3}/DST=xxx.xxx.xxx.xxx/g' file

See an online demo

Note that . chars should be escaped if you need to match literal dots.

The [0-9]{1,3} POSIX ERE compatible pattern (enabled with -E) will match 1, 2 or 3 digits.

To make sure you only match 3 digits at the end that are not followed with other digits, and that you are matching DST and not ADST, you may try adding word boundaries, \< and \>:

's/\<DST=123\.12\.12\.[0-9]{1,3}\>/DST=xxx.xxx.xxx.xxx/g'
   ^^                           ^^

Upvotes: 3

Related Questions