Extract filename and path from URL in bash script

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:
All of these tested on Bash 3.2.57(1)-release (x86_64-apple-darwin20)

FILE=/home/user/src/prog.c
echo ${FILE#/*/}  # ==> user/src/prog.c
echo ${FILE##/*/} # ==> prog.c
echo ${FILE##*/}  # ==> prog.c // Alternate version for some systems
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/)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)