A1g0r1thm
A1g0r1thm

Reputation: 75

Bash matching part of string

Say I have a string like

s1="sxfn://xfn.oxbr.ac.uk:8843/xfn/mech2?XFN=/castor/
    xf.oxbr.ac.uk/prod/oxbr.ac.uk/disk/xf20.m.ac.uk/prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst"

or

s2="sxfn://xfn.gla.ac.uk:8841/xfn/mech2?XFN=/castor/
    xf.gla.ac.uk/space/disk1/prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst"

and I want in my script to extract the last part starting from prod/ i.e. "prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst". Note that $s1 contains two occurrences of "prod/".

What is the most elegant way to do this in bash?

Upvotes: 1

Views: 65

Answers (3)

Jason Hu
Jason Hu

Reputation: 6333

sed can do it nicely:

s1="sxfn://xfn.oxbr.ac.uk:8843/xfn/mech2?XFN=/castor/xf.oxbr.ac.uk/prod/oxbr.ac.uk/disk/xf20.m.ac.uk/prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst"
echo "$s1" | sed 's/.*\/prod/\/prod/'

this relies on the earger matching of the .* part up front.

Upvotes: 0

anubhava
anubhava

Reputation: 784928

Using BASH string manipulations you can do:

echo "prod/${s1##*prod/}"
prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst

echo "prod/${s2##*prod/}"
prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst

Upvotes: 1

JNevill
JNevill

Reputation: 50019

With awk (which is a little overpowered for this, but it may be helpful if you have a file full of these strings you need to parse:

echo "sxfn://xfn.gla.ac.uk:8841/xfn/mech2?XFN=/castor/xf.gla.ac.uk/space/disk1/prod/v1.8/pienug_ib-2/reco_c21_dr3809_r35057.dst" | awk -F"\/prod" '{print "/prod"$NF}'

That's splitting the string by '/prod' then printing out the '/prod' delimiter and the last token in the string ($NF)

Upvotes: 0

Related Questions