user2477533
user2477533

Reputation: 201

Bash extract substring from a generic string

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...

Upvotes: 1

Views: 125

Answers (3)

anubhava
anubhava

Reputation: 784958

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

Upvotes: 4

clemens
clemens

Reputation: 17711

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.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295288

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

Upvotes: 3

Related Questions