Skip to content

Instantly share code, notes, and snippets.

@kmatt
Last active July 1, 2025 19:49
Show Gist options
  • Save kmatt/3e4bdd333a24726af9247ed3fe883081 to your computer and use it in GitHub Desktop.
Save kmatt/3e4bdd333a24726af9247ed3fe883081 to your computer and use it in GitHub Desktop.
Slug filenames in directory
#!/bin/bash
if [ "$#" -eq 0 ]; then
echo "Usage: $0 FILENAME | 'WILDCARD' (in single quotes)"
exit
fi
slug() {
# Replace non-alpha characters and rename file
f=$(basename "$1")
s=$(echo "$f" | awk '{ gsub(/[^0-9a-zA-Z_\-\. ]/, ""); gsub(/[ ]+/, "-"); gsub(/--+/, "-"); print; }')
if [ "$f" != "$s" ]; then
mv -v "$f" "$s"
fi
}
# Slug all filenames in current directory, this `find` invocation safe for paths with newline characters
find . -type f -depth 1 -name "$1" -print0 | while IFS= read -r -d '' fn; do slug "$fn"; done
# vim: set filetype=sh :
@kmatt
Copy link
Author

kmatt commented Jun 3, 2025

This may be a better use for find, but this works too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment