Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying bash string operators on a constant string

Tags:

string

bash

I'm trying to use bash string operators on a constant string. For instance, you can do the following on variable $foo:

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

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

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

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

[The reason I need to do this (rather than hardcoding the result of the substitution, ie. "c" here) is because I have a command template where a "%h" placeholder is replaced by something before running the command; the result of the substitution is seen as a constant by bash.]

like image 725
a3nm Avatar asked Feb 03 '12 14:02

a3nm


3 Answers

That's not possible using parameter expansion.

You could use other commands for this like sed/awk/expr.

but I don't see the requirement for this. You could just do:

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

Or if speed is not an issue, and you don't want to clutter the current environment with unneeded variables:

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

Anyway, you'd be better off using the command template to do the string manipulation or using something simple like cut:

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

Or more sophisticated like awk or sed:

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

Depends on what you need.

like image 61
estani Avatar answered Nov 19 '22 10:11

estani


You could use expr to get a similar result:

$ expr match "a:b:c" '.*:\(.*\)'
c
like image 42
jcollado Avatar answered Nov 19 '22 09:11

jcollado


You may be able to use Bash regex matching:

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

But why can't you do your template substitution into a variable assignment, then use the variable in the parameter expansion?

like image 1
Dennis Williamson Avatar answered Nov 19 '22 10:11

Dennis Williamson