1

I have string such as

username/ticket-12345/feature

and i want to extract just

ticket-12345

from bash. the forrmat of this string could be anything.... e.g.

'my string ticket-12345'

and 'ticket' could be a mixture of lower case and upper case. Is this possible to do from bash? I've tried searching for this particular case but i can't seem to find an answer...

3 Answers 3

4

Here is a pure bash regex method:

re='[[:alpha:]]+-[0-9]+'

s='username/ticket-12345/feature'
[[ $s =~ $re ]] && echo "${BASH_REMATCH[0]}"
ticket-12345

s='my string ticket-12345'
[[ $s =~ $re ]] && echo "${BASH_REMATCH[0]}"
ticket-12345
Sign up to request clarification or add additional context in comments.

4 Comments

Hmm. I may have hit "post" 15 seconds earlier, but I think you have the stronger answer; only functional difference between our approaches is whether ticket can be any alpha string, or can only consist of the letters T/t, I/i, C/c, K/k, and so forth
...that said, it'd be better to change from [A-Za-z] to [[:alpha:]], since the A-Z approach is collation-order/locale-dependent.
Yes that's right, probably this regex is too generic if OP wants only ticket in mixed cases.
At the time of writing, i didn't actually need a generic method, but this is perfect. Thanks!
3

The shell's built-in ERE (extended regular expression) support is adequate to the task:

ticket_re='[Tt][Ii][Cc][Kk][Ee][Tt]-[[:digit:]]+'
string='my string ticket-12345'

[[ $string =~ $ticket_re ]] && echo "Found ticket: ${BASH_REMATCH[0]}"

1 Comment

You can also use nocasematch with ticket-[[:digit:]]+ to ignore the case of "ticket", although that becomes awkward if you need to limit its scope to just this one match.
1

With the -o flag grep and its friends display only the found matches. You can use

egrep -io 'ticket-[0-9]+' file.txt

to find the tickets from your input text.

2 Comments

nod. Works (on most platforms, -o being a non-POSIX extension), as-updated -- whether this is more appropriate than the pure bash method depends on usage context (grep can scan through a large file much more quickly, but if each call is evaluating only a single line, then it'll be far slower than the shell-builtin alternative on account of the overhead required to fork and exec() an external process).
@CharlesDuffy: That's right, I will keep it and your solution in mind.

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.