Extract filename and path from URL in bash script

后端 未结 13 1199
别跟我提以往
别跟我提以往 2021-01-30 14:17

In my bash script I need to extract just the path from the given URL. For example, from the variable containing string:

http://login:password@example.com/one/more/dir/fi

13条回答
  •  青春惊慌失措
    2021-01-30 14:26

    Using only bash builtins:

    path="/${url#*://*/}" && [[ "/${url}" == "${path}" ]] && path="/"
    

    What this does is:

    1. remove the prefix *://*/ (so this would be your protocol and hostname+port)
    2. check if we actually succeeded in removing anything - if not, then this implies there was no third slash (assuming this is a well-formed URL)
    3. if there was no third slash, then the path is just /

    note: the quotation marks aren't actually needed here, but I find it easier to read with them in

提交回复
热议问题