sed plus sign doesn't work

RegexBashSed

Regex Problem Overview


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

variable="something/./././"
variable=$(echo $variable | sed "s/\/(\.\/)+/\//g")
echo $variable # this should output "something/"

When I tried to replace only /./ substring it worked with regex in sed \/\.\/. Does sed regex requires more flags to use multiplication of substring with + or *?

Regex Solutions


Solution 1 - Regex

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

$ variable="something/./././"
$ echo $variable | sed -r "s/\/(\.\/)+/\//g"
something/

Solution 2 - Regex

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

Solution 3 - Regex

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

Solution 4 - Regex

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ33nnView Question on Stackoverflow
Solution 1 - RegexfalsetruView Answer on Stackoverflow
Solution 2 - RegexScrutinizerView Answer on Stackoverflow
Solution 3 - Regexjaypal singhView Answer on Stackoverflow
Solution 4 - RegexMark SetchellView Answer on Stackoverflow