Last active
September 20, 2022 13:42
-
-
Save plasticine/16a44acbc1e1823499571d51360c5839 to your computer and use it in GitHub Desktop.
Slugify strings in bash with awk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Accepts an input string and slugifies it by replacing anything non-alphanumeric with a dash. | |
# | |
# Example; | |
# | |
# $ slugify "foo bar hello/world" | |
# > foo-bar-hello-world | |
# | |
# $ echo "foo bar hello/world" | slugify | |
# > foo-bar-hello-world | |
# | |
args=$* | |
[[ -p /dev/stdin ]] && { | |
mapfile -t | |
set -- "${MAPFILE[@]}" | |
set -- "$@" "$args" | |
} | |
echo -n "$*" | awk -f <(cat - <<-'AWK' | |
{ | |
gsub("^[ \t-]+", ""); | |
gsub("[ \t-]+$", ""); | |
gsub("[^a-zA-Z0-9]+", "-"); | |
print tolower($0) | |
} | |
AWK | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment