Search code examples
stringbashvariable-expansion

how to extract part of URL in bash using regx?


I am trying to extract part of url using bash regex . from below mentioned URL i just want to extract 124, which will always be between two hyphens .

http://abc-124-001.portal-ex.xyz-xyz.com:8091/

i tried doing following but i am looking for any better options to do this in one line

f=http://abc-124-001.portal-ex.xyz-xyz.com:8091/
f=${f#*-}
echo ${f%%-*}

op: 124

can this be done in one line or in any better way??


Solution

  • You can use cut:

    #!/bin/bash
    s='htt''p://abc-124-001.portal-ex.xyz-xyz.com:8091/'
    id=$(cut -d'-' -f2 <<< "$s")
    echo "$id"
    

    See the online demo.