Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed plus sign doesn't work

Tags:

regex

bash

sed

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 *?

like image 579
J33nn Avatar asked Feb 28 '14 15:02

J33nn


People also ask

What are the special characters in sed?

The special character in sed are the same as those in grep, with one key difference: the forward slash / is a special character in sed. The reason for this will become very clear when studying sed commands.

Does sed work on variable?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.

Can you use sed in a bash script?

Bash allows you to perform pattern replacement using variable expansion like (${var/pattern/replacement}). And so, does sed like this (sed -e 's/pattern/replacement/'). However, there is more to sed than replacing patterns in text files.

How do you use sed multiple times?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.


2 Answers

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

$ variable="something/./././"
$ echo $variable | sed -r "s/\/(\.\/)+/\//g"
something/
like image 88
falsetru Avatar answered Oct 08 '22 22:10

falsetru


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

like image 4
Scrutinizer Avatar answered Oct 08 '22 22:10

Scrutinizer