Extract filename and path from URL in bash script

后端 未结 13 971
别跟我提以往
别跟我提以往 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:42

    url="http://login:password@example.com/one/more/dir/file.exe?a=sth&b=sth"
    

    GNU grep

    $ grep -Po '\w\K/\w+[^?]+' <<<$url
    /one/more/dir/file.exe
    

    BSD grep

    $ grep -o '\w/\w\+[^?]\+' <<<$url | tail -c+2
    /one/more/dir/file.exe
    

    ripgrep

    $ rg -o '\w(/\w+[^?]+)' -r '$1' <<<$url
    /one/more/dir/file.exe
    

    To get other parts of URL, check: Getting parts of a URL (Regex).

提交回复
热议问题