Hyphen and underscore not compatible in sed

前端 未结 4 2017
傲寒
傲寒 2021-01-18 15:39

I\'m having trouble getting sed to recognize both hyphen and underscore in its pattern string.

Does anyone know why

[a-z|A-Z|0-9|\\-|_]
相关标签:
4条回答
  • 2021-01-18 15:58

    You don't need to use | symbol in a regex character class to separate the characters. Perhaps try something like this ...

    [a-zA-Z0-9\-_]
    
    0 讨论(0)
  • 2021-01-18 16:06

    As mentioned, you don't need anything to separate your ranges in a bracket expression. All that will do is adding | to the characters matched by the expression.

    Then, to add a hyphen, you can put it as the first or last character in the expression:

    [a-zA-Z0-9_-]
    

    And finally, ranges like a-z don't necessarily mean abcd...xyz, depending on your locale. You could use a POSIX character class instead:

    [[:alnum:]_-]
    

    Where [:alnum:] corresponds to all alphanumeric characters of your locale. In the C locale, it corresponds to 0-9A-Za-z.

    0 讨论(0)
  • 2021-01-18 16:09
    $ 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
    

    To match a hyphen in a character class, it must not be placed between two characters, otherwise it will be interpreted as a range operator. So to match a hyphen, place it at the beginning or end of the character class: and no escaping is necessary. See this answer for explanation: https://stackoverflow.com/a/4068725

    0 讨论(0)
  • 2021-01-18 16:22

    In my case, I wanted to replace a config setting that included a hyphen. Surrounding the setting in .* worked:

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

    Also works when the config setting has an underscore.

    0 讨论(0)
提交回复
热议问题