Parse URL in shell script

后端 未结 14 1744
一生所求
一生所求 2020-12-02 20:55

I have url like:

sftp://user@host.net/some/random/path

I want to extract user, host and path from this string. Any part can be random lengt

14条回答
  •  一向
    一向 (楼主)
    2020-12-02 21:32

    If you have access to Bash >= 3.0 you can do this in pure bash as well, thanks to the re-match operator =~:

    pattern='^(([[:alnum:]]+)://)?(([[:alnum:]]+)@)?([^:^@]+)(:([[:digit:]]+))?$'
    if [[ "http://us@cos.com:3142" =~ $pattern ]]; then
            proto=${BASH_REMATCH[2]}
            user=${BASH_REMATCH[4]}
            host=${BASH_REMATCH[5]}
            port=${BASH_REMATCH[7]}
    fi
    

    It should be faster and less resource-hungry then all the previous examples, because no external process is be spawned.

提交回复
热议问题