2

I try to find a substring of a string.

If I have the string try-30/16, I want to get the 30 string.

so I wrote the next:

n=${"'$b'":'-':'/'}

where $b is a variable I assign before this command. It gives the next:

bad substitution.

How I can do it?

2
  • 1
    What about awk? $ echo "try-30/16" | awk -F"[-/]" '{print $2}' Commented Jun 10, 2013 at 14:53
  • 1
    note that the parameter expansion you are using have this syntax ${parameter:offset:length}. It extracts substring based on index. The parameter expansion part of Bash manual is relevant here. Commented Jun 10, 2013 at 15:05

3 Answers 3

4

Try this.

b="try-30/16"
n=${b##*-}
n=${n%%/*}
echo $n
Sign up to request clarification or add additional context in comments.

2 Comments

+1. This is a good answer, but could still be improved by pointing to Parameter Expansion documentation.
Though it wouldn't matter for OP's question, but ## and %% removes the longest match. We can do with just # and % in this particular case.
2
$ n=${b%/*}
$ n=${n#*-}
$ echo $n
30

Comments

2

You can also do:

[[ $b =~ [^-]+-([0-9]+) ]] && echo "${BASH_REMATCH[1]}"

OUTPUT:

30

Live Demo: http://ideone.com/bKHGcS

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.