duncan­lock­.net

Good, simple, Bash slugify function

# Slugify
  # Transliterate everything to ASCII
  # Strip out apostrophes
  # Anything that's not a letter or number to a dash
  # Strip leading & trailing dashes
  # Everything to lowercase
function slugify() {
  iconv -t ascii//TRANSLIT \
  | tr -d "'" \
  | sed -E 's/[^a-zA-Z0-9]+/-/g' \
  | sed -E 's/^-+|-+$//g' \
  | tr "[:upper:]" "[:lower:]"
}

This is point-free style – so, once you’ve declared it, you can use it in a pipe, like this:

title="This is my long Title, with some Punctuation!?"
title_slug=$(echo "$title" | slugify)

or like this:

$ echo "This is my long Title, with some Punctuation!?" | slugify
this-is-my-long-title-with-some-punctuation

References


Related Posts