5

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.

1
  • 1
    I don't think that's possible.
    – Daniel Beck
    Jan 7, 2012 at 15:24

2 Answers 2

5

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]}
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .