extract path value substring using sed

Trying to extract text between a path variable which has the following value
path_value="path/to/value/src"
I want to extract just value from the above variable and use that later in my script. I know it can be done using grep or awk but I wanted to know how it can be done using sed

So I tried this
service_name=$(echo $path_value | sed -e 's/path/to/(.*\)/.*/\1/')
But I get this error bad flag in substitute command: '('

Could you please suggest what is the right regex to achieve what I am trying to do?

>Solution :

You can use

#!/bin/bash
path_value="path/to/value/src"
service_name=$(echo "$path_value" | sed 's~path/to/\([^/]*\)/.*~\1~')
echo "$service_name"
# => value

See the online demo.

Note I replaced / regex delimiters with ~ so as to avoid escaping / chars inside the pattern.

The capturing parentheses must both be escaped in a POSIX BRE regex.

The [^/]* part only matches zero or more chars other than /.

Leave a Reply