简体   繁体   English

使用sed使用正则表达式替换IP

[英]Using sed to replace IP using regex

Assuming a simple text file: 假设一个简单的文本文件:

123.123.123.123

I would like to replace the IP inside of it with 222.222.222.222 . 我想用222.222.222.222替换其中的IP。 I have tried the below but nothing changes, however the same regex seems to work in this Regexr 我已经尝试了以下内容,但没有任何变化,但是相同的正则表达式似乎可以在此Regexr中工作

sed -i '' 's/(\d{1,3}\.){3}\d{1,3}/222.222.222.222/' file.txt

Am I missing something? 我想念什么吗?

Two problems here: 这里有两个问题:

  • sed doesn't like PCRE digit property \\d , use range: [0-9] or POSIX [[:digit:]] sed不喜欢PCRE digit属性\\d ,使用范围: [0-9]或POSIX [[:digit:]]
  • You need to use -r flag for extended regex as well. 您还需要对扩展的正则表达式使用-r标志。

This should work: 这应该工作:

s='123.123.123.123'
sed -r 's/([0-9]{1,3}\.){3}[0-9]{1,3}/222.222.222.222/' <<< "$s"
222.222.222.222

Better would be to use anchors to avoid matching unexpected input: 更好的方法是使用锚,以避免匹配意外的输入:

sed -r 's/^([0-9]{1,3}\.){3}[0-9]{1,3}$/222.222.222.222/' <<< "$s"

PS: On OSX use -E instead of -r : PS:在OSX上,请使用-E而不是-r

sed -E 's/^([0-9]{1,3}\.){3}[0-9]{1,3}$/222.222.222.222/' <<< "$s"
222.222.222.222

You'd better use -r , as indicated by anubhava. 如anubhava所示,最好使用-r

But in case you don't have it, you have to escape every single ( , ) , { and } . 但是,如果没有,就必须转义每个(){} And also, use [0-9] instead of \\d : 而且,使用[0-9]代替\\d

$ sed 's/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/222.222.222.222/' <<< "123.123.123.123"
222.222.222.222

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

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