Issue
I am trying to replace part of the string, but can not find a proper regex for sed to execute it properly.
I have a string
/abc/foo/../bar
And I would like to achive the following result:
/abc/bar
I have tried to do it using this command:
echo $string | sed 's/\/[^:-]*\..\//\//'
But as result I am getting just /bar
.
I understand that I must use group, but I just do not get it. Could you, please, help me to find out this group that could be used?
Solution
You can use
#!/bin/bash
string='/abc/foo/../bar'
sed -nE 's~^(/[^/]*)(/.*)?/\.\.(/[^/]*).*~\1\3~p' <<< "$string"
See the online demo. Details:
-n
- suppresses default line outputE
- enables POSIX ERE regex syntax^
- start of string(/[^/]*)
- Group 1: a/
and then zero or more chars other than/
(/.*)?
- an optional group 2: a/
and then any text/\.\.
- a/..
fixed string(/[^/]*)
- Group 3: a/
and then zero or more chars other than/
.*
- the rest of the string.\1\3
replaces the match with Group 1 and 3 values concatenatedp
only prints the result of successful substitution.
Answered By - Wiktor Stribiżew Answer Checked By - Candace Johnson (WPSolving Volunteer)