简体   繁体   English

查找并用sed替换IP地址的最后一段

[英]Finding and replacing last segment of ip addresses with sed

I have bunch of json files that contains web events. 我有一堆包含网络事件的json文件。 Each event contains lots of stuff and I'm trying to do ip address anonymization (replacing last segment of ip addresses with 0) with sed . 每个事件包含很多东西,我正在尝试使用sed进行IP地址匿名化(将IP地址的最后一段替换为0)。

In short: 简而言之:

How to find substrings like "ip":"34.542.3.34" from json files and transform them to "ip":"34.542.3.0" ? 如何从json文件中找到像"ip":"34.542.3.34"这样的子字符串并将其转换为"ip":"34.542.3.0"

Attempts: 尝试:

  1. Resetting starting point with \\K \\K重置起点

sed -e 's/"ip":"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.\\K[0-9]{1,3}/0/g' file.json

This would work but unfortunately sed doesn't seem support reseting starting point. 这将起作用,但不幸的是, sed似乎不支持重置起点。

  1. Negative lookbehind 负向后看

sed -e 's/(?<="ip":"[0-9]{3}\\.[0-9]{3}\\.[0-9]{3}\\.)([0-9]{3})/0/g' file.json

This would also work but negative lookbehind doesn't seem to support non-fixed-width assortions. 这也可以工作,但是负向后看似乎不支持非固定宽度的分类。 So [0-9]{1,3} is not supported and hence this won't work. 因此,不支持[0-9]{1,3} ,因此将无法使用。

  1. Matching groups 匹配组

Third idea was to use matching groups and do something like this 第三个想法是使用匹配的组并执行类似的操作

sed -e 's/("ip":"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|([0-9]{1,3})/\\1\\20/g' file.json

But couldn't figure out how this would actually work with sed . 但是无法弄清楚sed实际如何工作。

  1. Writing regex for every possible length option separately 为每种可能的长度选项分别编写正则表达式

This would probably work but it would make regex too long and hardly readable. 这可能会起作用,但是会使正则表达式太长且难以阅读。 I would like to find more convenient and clean solution. 我想找到更方便和干净的解决方案。

Any suggestions? 有什么建议么?

使用GNU sed:

sed -r 's/("ip":"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)[0-9]{1,3}(")/\10\2/' file

如果没有-r -option:

sed -e 's/\("ip":"[[:digit:]]\{1,3\}\(\.[[:digit:]]\{1,3\}\)\{2\}\.\)\([[:digit:]]\{1,3\}\)"/\10"/g' tst.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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