Trimming And Replacing
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 17 of 39.
Bash can cut a pattern off either end of a value. % removes the shortest match from the end and %% the longest. # and ## do the same from the start. Patterns use the wildcards you know from file names: * matches any text.
photo="beach.2026.jpeg"
echo "${photo%.jpeg}" # beach.2026
echo "${photo%.*}" # beach.2026
echo "${photo%%.*}" # beach
path="home/ana/pics/cat.png"
echo "${path#*/}" # ana/pics/cat.png
echo "${path##*/}" # cat.png${path##*/} is the file name and ${path%/*} is the folder it sits in, home/ana/pics.
To change text inside a value, ${s/old/new} replaces the first match and ${s//old/new} replaces every match:
s="red red blue"
echo "${s/red/green}" # green red blue
echo "${s//red/green}" # green green blueLike slicing, these expansions leave the variable unchanged.
Challenge
MediumWrite a script that splits a log file's path into parts.
- Open
paths.sh. Its first argument is a path such aslogs/web/access.2026.log. - Print
File:followed by the file name: everything after the last/. - Print
Folder:followed by everything before the last/. - Print
Name:followed by the file name up to its first dot. - Print
Safe:followed by the file name with every.replaced by_. - Save the file.
Try it: run bash paths.sh logs/web/access.2026.log. It prints:
File: access.2026.log
Folder: logs/web
Name: access
Safe: access_2026_logThen run bash paths.sh notes/todo.txt, with one folder and one dot:
File: todo.txt
Folder: notes
Name: todo
Safe: todo_txtTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV ReportPractice on your own: Terminal playground