使用纯 bash 创建 URL 友好的 slug



我追求一个纯粹的 bash 解决方案来"蛞蝓化"一个变量,这并不像我的那么丑陋。

slugify:小写,缩短为 63 个字节,除了 0-9 和 a-z 替换为 -。没有前导/尾随-。结果是适合在 URL 主机名和域名中使用的字符串。 输入很可能是一系列带有不需要的字符的单词,例如:

'Effrafax_mUKwT'uP7(Garkbit<\1}@NJ"RJ"Hactar*S;-H%x.?oLazlarl(=Zss@c9?qick.:?BZarquonelW{x>g@'k'

其中的鼻涕虫看起来像: 'Effrafax-mukwt-up7-garkbit-1-NJRJHACTAR-s-h-x-olazlarl-zss-c9-q'

slugify () {
  next=${1//+([^A-Za-z0-9])/-}
  next=${next:0:63}
  next=${next,,}
  next=${next#-}
  next=${next%-}
  echo $next
}

另外为什么${next//^-|-$}不去掉前缀和后缀'-'?其他建议?

我在我的 bash 配置文件中使用了这个函数:

slugify () {
    echo "$1" | iconv -t ascii//TRANSLIT | sed -r s/[~^]+//g | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+|-+$//g | tr A-Z a-z
}

基于: https://gist.github.com/oneohthree/f528c7ae1e701ad990e6

上面

答案的OS X和Linux兼容变体

slugify () {
    echo "$1" | iconv -c -t ascii//TRANSLIT | sed -E 's/[~^]+//g' | sed -E 's/[^a-zA-Z0-9]+/-/g' | sed -E 's/^-+|-+$//g' | tr A-Z a-z
}

最新更新