Expansion and Data
String Cleanup
Paths and Names
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"
path ← /var/log/app/access log.txt
3path="/var/log/app/access log.txt"4file="${path##*/}"values this step/var/log/app/access log.txtpathfile ← access log.txt
3path="/var/log/app/access log.txt"4file="${path##*/}"5name="${file%.*}"values this stepaccess log.txtfile/var/log/app/access log.txtpathname ← access log
4file="${path##*/}"5name="${file%.*}"6slug="${name// /_}"values this stepaccess lognameaccess log.txtfileslug ← access_log
5name="${file%.*}"6slug="${name// /_}"7echo "$slug"values this stepaccess_logslugaccess lognameecho "$slug"
6slug="${name// /_}"7echo "$slug"outputaccess_logvalues this stepaccess_logslug
Follow the Cleanup
pathstarts as/var/log/app/access log.txt.- Removing the path prefix leaves
fileasaccess log.txt. - Removing the
.txtsuffix leavesnameasaccess log. - Replacing the space with
_makesslugequalaccess_log. - 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.