Skip to the workspace
Pebellslearn by building
Arguments and String Manipulation  ›  Lesson

Trimming, Replacing and Changing Case

Pattern replacement 14 minParameter 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.

shell bash / Trimming, Replacing and Changing Case

Explore each scene at your own pace.

01 · The rule

The rule

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 end

Single # 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 match

Changing case (Bash 4 and later):

echo "${n,,}"          # my notes 2
echo "${n^^}"          # MY NOTES 2

Putting it together for backup.sh:

src="${src%/}"          # /home/asha/My Notes
name="${src##*/}"       # My Notes
name="${name// /_}"     # My_Notes
name="${name,,}"        # my_notes
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.