Trimming, Replacing and Changing Case
Parameter expansion trims a pattern from the start with #, from the end with %, replaces with /, and changes letter case with ^^ and ,, in Bash 4 and later.
Apply shell patterns to trim or replace text without confusing them with regular expressions.
backup.sh is given /home/asha/My Notes/ and should name the archive my_notes: just the last folder name, no trailing slash, underscores instead of spaces, all lowercase. Four small parameter expansions do the whole job without starting a single extra program.
The rule
#trims the front,%trims the end,/replaces inside.
The patterns are the same wildcards you use for file names: * matches anything, ? one character.
file=report.tar.gz
echo "${file#*.}" # tar.gz shortest match of *. removed from the front
echo "${file##*.}" # gz longest match removed from the front
echo "${file%.*}" # report.tar shortest match of .* removed from the end
echo "${file%%.*}" # report longest match removed from the endSingle # or % removes the shortest match; doubled removes the longest.
Replacing:
n="My Notes 2"
echo "${n/ /_}" # My_Notes 2 first match only
echo "${n// /_}" # My_Notes_2 every matchChanging case (Bash 4 and later):
echo "${n,,}" # my notes 2
echo "${n^^}" # MY NOTES 2Putting it together for backup.sh:
src="${src%/}" # /home/asha/My Notes
name="${src##*/}" # My Notes
name="${name// /_}" # My_Notes
name="${name,,}" # my_notes