Parameter expansion can remove path prefixes, trim suffixes, and replace characters without spawning another command.

Program

Play the script to watch a path become a filename, then a report name, then a shell-safe slug.

string_cleanup.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

path="/var/log/app/access log.txt"
file="${path##*/}"
name="${file%.*}"
slug="${name// /_}"
echo "$slug"
  1. path ← /var/log/app/access log.txt

    3path="/var/log/app/access log.txt"4file="${path##*/}"
    values this step/var/log/app/access log.txtpath
  2. file ← access log.txt

    3path="/var/log/app/access log.txt"4file="${path##*/}"5name="${file%.*}"
    values this stepaccess log.txtfile/var/log/app/access log.txtpath
  3. name ← access log

    4file="${path##*/}"5name="${file%.*}"6slug="${name// /_}"
    values this stepaccess lognameaccess log.txtfile
  4. slug ← access_log

    5name="${file%.*}"6slug="${name// /_}"7echo "$slug"
    values this stepaccess_logslugaccess logname
  5. echo "$slug"

    6slug="${name// /_}"7echo "$slug"
    outputaccess_log
    values this stepaccess_logslug

Follow the Cleanup

  1. path starts as /var/log/app/access log.txt.
  2. Removing the path prefix leaves file as access log.txt.
  3. Removing the .txt suffix leaves name as access log.
  4. Replacing the space with _ makes slug equal access_log.
  5. The script prints access_log. | value name | value | | --- | --- | | path | /var/log/app/access log.txt | | file | access log.txt | | name | access log | | slug | access_log |
prefix removal `${path##*/}` removes the longest prefix ending in `/`, leaving a filename.
suffix removal `${file%.*}` removes the shortest suffix that starts with a dot.
substitution `${name// /_}` replaces every space with an underscore.

Exercise: string_cleanup.sh

Reproduce the output access_log, then change the filename text and predict the slug before running it.