Search code examples
parsingshellurl

Parse URL in shell script


I have url like:

sftp://[email protected]/some/random/path

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


Solution

  • Using Python (best tool for this job, IMHO):

    #!/usr/bin/env python
    
    import os
    from urlparse import urlparse
    
    uri = os.environ['NAUTILUS_SCRIPT_CURRENT_URI']
    result = urlparse(uri)
    user, host = result.netloc.split('@')
    path = result.path
    print('user=', user)
    print('host=', host)
    print('path=', path)
    

    Further reading: