Vladimir Panchenko
Vladimir Panchenko

Reputation: 1193

How to extract value from the string in bash?

I have an input string in the following format:

bugfix/ABC-12345-1-00

I want to extract "ABC-12345". Regex for that format in C# looks like this:

.\*\\/([A-Z]+-[0-9]+).\*

How can I do that in a bash script? I've tried sed and awk but had no success because I need to extract value from the capturing group and skip the rest.

Upvotes: 2

Views: 456

Answers (4)

Jotne
Jotne

Reputation: 41456

If you do not like to use regex, you can use this awk:

echo "bugfix/ABC-12345-1-00" | awk -F\/ '{print $NF}'
ABC-12345-1-00

Or just this:

awk -F\/ '$0=$NF'

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

If your grep supports -P then you could use the below grep commands.

$ echo 'bugfix/ABC-12345-1-00' | grep -oP '/\K[A-Z]+-\d+'
ABC-12345

\K keeps the text matched so far out of the overall regex match.

$ echo 'bugfix/ABC-12345-1-00' | grep -oP '(?<=/)[A-Z]+-\d+'
ABC-12345

(?<=/) Positive lookbehind which asserts that the match must be preceded by a / symbol.

Through sed,

$ echo 'bugfix/ABC-12345-1-00' | sed 's~.*/\([A-Z]\+-[0-9]\+\).*~\1~'
ABC-12345

Upvotes: 5

SMA
SMA

Reputation: 37023

You could try something like:

echo "bugfix/ABC-12345-1-00" | egrep -o '[A-Z]+-[0-9]+'
OUTPUT:
ABC-12345

Upvotes: 0

Vihari Piratla
Vihari Piratla

Reputation: 9332

echo "bugfix/ABC-12345-1-00"| perl -ane '/.*?([A-Z]+\-[0-9]+).*/;print $1."\n"'

Upvotes: 2

Related Questions