Unix & Linux Asked by erenon on November 26, 2021
I’m looking for the simplest solution that takes $*
as input, and expands to each element prefixed and suffixed with a given string:
$*=foo bar baz
<solution(x,y)>=xfooy xbary xbazy
I can do either prepending or appending, but not both:
echo ${*/#/x}
# prints xfoo xbar xbaz
echo ${*/%/y}
# prints fooy bary bazy
I’m unable to combine the two solutions. The documentation claims the value returned by the expansion in the parameter=* case is a list, but I’m unable to use it as such. I want to pass the resulting array of values to a further command as separate arugments, therefore simply building a single string wouldn’t work.
Given a list in $@
... print it
set -- foo bar baz
printf '%sn' "$@"
foo
bar
baz
... perform a list op
set -- $(printf 'x%sy ' "$@")
printf '%sn' "$@"
xfooy
xbary
xbazy
... stringify list
printf '%sn' "$*"
xfooy xbary xbazy
No special bash features involved.
Answered by martin8guest on November 26, 2021
${var/pattern/replacement}
is a ksh93 parameter expansion operator, also supported by zsh
, mksh
, and bash
, though with variations (mksh
's currently can't operate on arrays).
In ksh93
, you'd do ${var/*/x y}
to prefix the expansion of $var
with x
and suffix with y
, and ${array[@]/*/x y}
to do that for each element of the array.
So, for the array of positional parameters:
print -r -- "${@/*/x y}"
(beware however that like for your ${*/#/x}
, it's buggy when the list of positional parameters is empty).
zsh
's equivalent of ksh93
's