Search code examples
bashstring-matching

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?


Solution

  • 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