Using bash string operators in a constant string

I am trying to use bash string operators in a constant string. For example, you can do the following in the variable $ foo:

$ foo=a:b:c; echo ${foo##*:}
c

Now, if the string "a: b: c" is constant, I would like to have a more concise solution, for example:

echo ${"a:b:c"##*:}

However, this is not valid bash syntax. Is there any way to accomplish this?

[The reason I need to do this (instead of hard-coding the substitution result, that is, "c" here) is because I have a command template where the substitute "% h" is replaced with something before running the command ; the substitution result is considered a constant in bash.]

+5
source share
3 answers

This is not possible using the parameter extension.

, sed/awk/expr.

. :

tmp=%h
echo ${tmp##*:}

, , :

(tmp=%h; echo ${tmp##*:})

, - , cut:

# get third filed delimited by :
$ cut -d: -f3<<<'a:b:c'
c

, awk sed:

#get last field separated by ':'
$ awk -F: '{print $NF}'<<<'a:b:c'
c
$ sed 's/.*:\([^:]*\)/\1/'<<<'a:b:c'
c

, .

+4

expr, :

$ expr match "a:b:c" '.*:\(.*\)'
c
+2

You might be able to use Bash regex matching:

pattern='.*:([^:]+)$'
[[ "a:b:c" =~ $pattern ]]
echo "${BASH_REMATCH[1]}"

But why can't you replace the template with an assignment to a variable and then use the variable in the parameter extension?

+1
source

All Articles