Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested parameter substitution in POSIX shell

Tags:

posix

sh

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
like image 825
benizi Avatar asked Nov 22 '25 00:11

benizi


1 Answers

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.

like image 82
chepner Avatar answered Nov 24 '25 23:11

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!