Skip to content

Instantly share code, notes, and snippets.

@plasticine
Last active September 20, 2022 13:42
Show Gist options
  • Save plasticine/16a44acbc1e1823499571d51360c5839 to your computer and use it in GitHub Desktop.
Save plasticine/16a44acbc1e1823499571d51360c5839 to your computer and use it in GitHub Desktop.
Slugify strings in bash with awk
#!/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