连字符和下划线在SED中不兼容



我很难在其模式字符串中识别连字符和下划线。

有人知道为什么

[a-z|A-Z|0-9|-|_]

在下面的示例中,例如

[a-z|A-Z|0-9|_]

$  cat /tmp/sed_undescore_hypen
lkjdaslf lkjlsadjfl dfpasdiuy service-type = service-1; jaldkfjlasdjflk address = address1; kldjfladsf
lkjdaslf lkjlsadjfl dfasdf  service-type = service_1; jaldkfjlasdjflk address = address1; kldjfladsf
$  sed 's/.*(service-type = [a-z|A-Z|0-9|-|_]*);.*(address = .*);.*/1    2/g' /tmp/sed_undescore_hypen
lkjdaslf lkjlsadjfl dfpasdiuy service-type = service-1; jaldkfjlasdjflk address = address1; kldjfladsf
service-type = service_1    address = address1
$  sed 's/.*(service-type = [a-z|A-Z|0-9|-]*);.*(address = .*);.*/1    2/g' /tmp/sed_undescore_hypen
service-type = service-1    address = address1
lkjdaslf lkjlsadjfl dfasdf  service-type = service_1; jaldkfjlasdjflk address = address1; kldjfladsf
$  sed 's/.*(service-type = [a-z|A-Z|0-9|_]*);.*(address = .*);.*/1    2/g' /tmp/sed_undescore_hypen
lkjdaslf lkjlsadjfl dfpasdiuy service-type = service-1; jaldkfjlasdjflk address = address1; kldjfladsf
service-type = service_1    address = address1

如前所述,您不需要任何东西就可以在括号表达式中分离范围。要做的就是将|添加到与表达式匹配的字符中。

然后,要添加连字符,您可以将其列为表达式中的第一个或最后一个字符:

[a-zA-Z0-9_-]

最后,像a-z这样的范围不一定是指abcd...xyz,具体取决于您的语言环境。您可以使用POSIX字符类:

[[:alnum:]_-]

[:alnum:]对应于您的语言环境的所有字母数字字符。在C语言环境中,它对应于0-9A-Za-z

您不需要在Regex字符类中使用|符号将字符分开。也许尝试这样的事情...

[a-zA-Z0-9-_]
$ sed 's/.*(service-type = [a-z|A-Z|0-9|_-]*);.*(address = .*);.*/1    2/g' sed_underscore_hypen.txt
service-type = service-1    address = address1
service-type = service_1    address = address1
pknga_000@miro MINGW64 ~/Documents
$ sed 's/.*(service-type = [-a-z|A-Z|0-9|_]*);.*(address = .*);.*/1    2/g' sed_underscore_hypen.txt
service-type = service-1    address = address1
service-type = service_1    address = address1

要匹配字符类中的连字符,不得将其放置在两个字符之间,否则将其解释为范围运算符。因此,要匹配连字符,请将其放在角色类的开始或结尾处:不需要逃脱。有关说明:https://stackoverflow.com/a/4068725

请参阅此答案。

在我的情况下,我想替换包含连字符的配置设置。围绕.*中的设置工作:

sed 's/.*some-service.*/some-service="new-value"/g' file

当配置设置具有下划线时也可以工作。

相关内容

  • 没有找到相关文章

最新更新