6

我无法让 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
4

4 回答 4

11

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

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

[a-zA-Z0-9_-]

最后,范围a-z不一定意味着abcd...xyz,具体取决于您的语言环境。您可以改用 POSIX 字符类:

[[:alnum:]_-]

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

于 2017-03-12T05:25:57.880 回答
0

您不需要在正则表达式字符类|中使用符号来分隔字符。也许尝试这样的事情......

[a-zA-Z0-9\-_]
于 2017-03-12T05:08:19.337 回答
0
$ 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

于 2017-03-12T05:21:26.333 回答
0

就我而言,我想替换一个包含连字符的配置设置。围绕.*工作中的设置:

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

当配置设置有下划线时也有效。

于 2020-07-12T20:26:18.830 回答