Menu
CoddyTech

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 blue

Like slicing, these expansions leave the variable unchanged.

challenge icon

Challenge

Medium

Write a script that splits a log file's path into parts.

  1. Open paths.sh. Its first argument is a path such as logs/web/access.2026.log.
  2. Print File: followed by the file name: everything after the last /.
  3. Print Folder: followed by everything before the last /.
  4. Print Name: followed by the file name up to its first dot.
  5. Print Safe: followed by the file name with every . replaced by _.
  6. 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_log

Then run bash paths.sh notes/todo.txt, with one folder and one dot:

File: todo.txt
Folder: notes
Name: todo
Safe: todo_txt

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground