Extract filename and path from URL in bash script

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

    There are built-in functions in bash to handle this, e.g., the string pattern-matching operators:

    1. '#' remove minimal matching prefixes
    2. '##' remove maximal matching prefixes
    3. '%' remove minimal matching suffixes
    4. '%%' remove maximal matching suffixes

    For example:

    FILE=/home/user/src/prog.c
    echo ${FILE#/*/}  # ==> user/src/prog.c
    echo ${FILE##/*/} # ==> prog.c
    echo ${FILE%/*}   # ==> /home/user/src
    echo ${FILE%%/*}  # ==> nil
    echo ${FILE%.c}   # ==> /home/user/src/prog
    

    All this from the excellent book: "A Practical Guide to Linux Commands, Editors, and Shell Programming by Mark G. Sobell (http://www.sobell.com/)

提交回复
热议问题