duncanlock.net

Good, simple, Bash slugify function

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


Comments