sed plus sign doesn't work

后端 未结 4 1424
你的背包
你的背包 2020-12-01 15:53

I\'m trying to replace /./ or /././ or /./././ to / only in bash script. I\'ve managed to create regex for sed but it doe

相关标签:
4条回答
  • 2020-12-01 16:08

    Use -r option to make sed to use extended regular expression:

    $ variable="something/./././"
    $ echo $variable | sed -r "s/\/(\.\/)+/\//g"
    something/
    
    0 讨论(0)
  • 2020-12-01 16:08

    Two things to make it simple:

    $ variable="something/./././"
    $ sed -r 's#(\./){1,}##' <<< "$variable"
    something/
    
    • Use {1,} to indicate one or more patterns. You won't need g with this.
    • Use different delimiterers # in above case to make it readable
    • + is ERE so you need to enable -E or -r option to use it
    0 讨论(0)
  • 2020-12-01 16:14

    You can also do this with bash's built-in parameter substitution. This doesn't require sed, which doesn't accept -r on a Mac under OS X:

    variable="something/./././"
    a=${variable/\/*/}/                   # Remove slash and everything after it, then re-apply slash afterwards
    echo $a
    something/
    

    See here for explanation and other examples.

    0 讨论(0)
  • 2020-12-01 16:15

    Any sed:

    sed 's|/\(\./\)\{1,\}|/|g'
    

    But a + or \{1,\} would not even be required in this case, a * would do nicely, so

    sed 's|/\(\./\)*|/|g'
    

    should suffice

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