I use ${parameter#word}
and ${parameter%word}
to remove prefix and postfix of string.
$ x=2012-hello.jpg
$ y=${x#*-}
$ z=${y%.*}
$ echo $z
hello
How can I do them at once instead of two.
It is not possible with parameter expansion, but it is possible with regular expression matching:
x=2012-hello.jpg
[[ $x =~ .*-(.*)\.jpg ]] && echo ${BASH_REMATCH[1]}
If you are OK with using sed
instead of parameter expansion:
x=2012-hello.jpg
$ z="$(sed -e 's/.*-\(.*\)\..*/\1/' <<<"$x")"
$ echo "$z"
hello