Home > Software design >  extract path value substring using sed
extract path value substring using sed

Time:05-01

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?

CodePudding user response:

Using parameter substitution and eliminating the subprocess calls:

$ path_value="path/to/value/src"

$ tempx="${path_value%/*}"
$ echo "${tempx}"
path/to/value

$ service_name="${tempx##*/}"
$ echo "${service_name}"
value

Performing a bash/regex comparison and retrieving the desired item from the BASH_REMATCH[] array (also eliminates subprocess calls):

$ regex='.*/([^/] )/([^/] )$'
$ [[ "${path_value}" =~ $regex ]] && service_name="${BASH_REMATCH[1]}"
$ echo "${service_name}"

# fwiw, contents of the BASH_REMATCH[] array:

$ typeset -p BASH_REMATCH
declare -ar BASH_REMATCH=([0]="path/to/value/src" [1]="value" [2]="src")

CodePudding user response:

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 /.

  • Related