Parse URL in shell script

后端 未结 14 1714
一生所求
一生所求 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:52

    I did further parsing, expanding the solution given by @Shirkrin:

    #!/bin/bash
    
    parse_url() {
        local query1 query2 path1 path2
    
        # extract the protocol
        proto="$(echo $1 | grep :// | sed -e's,^\(.*://\).*,\1,g')"
    
        if [[ ! -z $proto ]] ; then
                # remove the protocol
                url="$(echo ${1/$proto/})"
    
                # extract the user (if any)
                login="$(echo $url | grep @ | cut -d@ -f1)"
    
                # extract the host
                host="$(echo ${url/$login@/} | cut -d/ -f1)"
    
                # by request - try to extract the port
                port="$(echo $host | sed -e 's,^.*:,:,g' -e 's,.*:\([0-9]*\).*,\1,g' -e 's,[^0-9],,g')"
    
                # extract the uri (if any)
                resource="/$(echo $url | grep / | cut -d/ -f2-)"
        else
                url=""
                login=""
                host=""
                port=""
                resource=$1
        fi
    
        # extract the path (if any)
        path1="$(echo $resource | grep ? | cut -d? -f1 )"
        path2="$(echo $resource | grep \# | cut -d# -f1 )"
        path=$path1
        if [[ -z $path ]] ; then path=$path2 ; fi
        if [[ -z $path ]] ; then path=$resource ; fi
    
        # extract the query (if any)
        query1="$(echo $resource | grep ? | cut -d? -f2-)"
        query2="$(echo $query1 | grep \# | cut -d\# -f1 )"
        query=$query2
        if [[ -z $query ]] ; then query=$query1 ; fi
    
        # extract the fragment (if any)
        fragment="$(echo $resource | grep \# | cut -d\# -f2 )"
    
        echo "url: $url"
        echo "   proto: $proto"
        echo "   login: $login"
        echo "    host: $host"
        echo "    port: $port"
        echo "resource: $resource"
        echo "    path: $path"
        echo "   query: $query"
        echo "fragment: $fragment"
        echo ""
    }
    
    parse_url "http://login:password@example.com:8080/one/more/dir/file.exe?a=sth&b=sth#anchor_fragment"
    parse_url "https://example.com/one/more/dir/file.exe#anchor_fragment"
    parse_url "http://login:password@example.com:8080/one/more/dir/file.exe#anchor_fragment"
    parse_url "ftp://user@example.com:8080/one/more/dir/file.exe?a=sth&b=sth"
    parse_url "/one/more/dir/file.exe"
    parse_url "file.exe"
    parse_url "file.exe#anchor"
    

提交回复
热议问题