Reputation: 4216
Nesting parameter substitutions works in Zsh:
$ param=abc
# nested remove prefix ${...#a} and remove suffix ${...%c} =>
$ printf '%s\n' ${${param#a}%c}
# => b
Is there any equivalent in POSIX?
$ param=abc
$ printf '%s\n' ${${param#a}%c}
# => dash: 2: Bad substitution
# => sh: ${${param#a}%c}: bad substitution
# => bash: ${${param#a}%c}: bad substitution
Upvotes: 3
Views: 1046
Reputation: 531858
You can use expr
instead to extract the text between the desired prefix and suffix. (This is not, of course, a general purpose equivalent to nested expressions, but does solve your given problem.)
param=abc
expr "$param" : "a\(.*\)c"
The regular expression matching operator :
of expr
takes two arguments: the left argument is a string, the right argument is a regular expression. The output is whatever is matched inside the \(...\)
group.
Upvotes: 3
Reputation: 1
Bash does not, but you have a host of other tools that can get the job done.
cut -b2 <<< abc
tr -d ac <<< abc
sed s/[ac]// <<< abc
awk '$0=$2' FS= <<< abc
It should be noted that parameter substitution does not scale
Parameter expansion slow for large data sets
Upvotes: 1