Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
1  
I don't think that's possible. –  Daniel Beck Jan 7 '12 at 15:24

2 Answers 2

up vote 4 down vote accepted

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]}
share|improve this answer

If you are OK with using sed instead of parameter expansion:

x=2012-hello.jpg
$ z="$(sed -e 's/.*-\(.*\)\..*/\1/' <<<"$x")"
$ echo "$z"
hello
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.