There are built-in functions in bash to handle this, e.g., the string pattern-matching operators:
- ‘#’ remove minimal matching prefixes
- ‘##’ remove maximal matching prefixes
- ‘%’ remove minimal matching suffixes
- ‘%%’ 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/)