bash - 使用纯 bash 创建 URL 友好的 slug?

标签 bash slug parameter-expansion

我正在寻找一个纯 bash 解决方案来“slugify”一个变量,而且它不像我的那样难看。

slugify: lowercased, shortened to 63 bytes, and with everything except 0-9 and a-z replaced with -. No leading / trailing -. A string suitable to use in URL hostnames and domain names is the result. An input is most likely a series of words with undesired characters in throughout such as:

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

Of which a slug would look like: '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

关于bash - 使用纯 bash 创建 URL 友好的 slug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050589/

相关文章:

用于用户提示的 Linux 函数

linux - 按编号顺序创建第一个不存在的文件

php - 清理放置在 URL 中的字符串的最佳方法是什么,例如 SO 上的问题名称?

javascript - 如何将 "slugified-title"转换为 "Slugified Title"

bash - ${v^^} 和 ${v@U} 的区别?

Bash shopt xpg_echo

bash - 通过SSH在远程Linux服务器上运行命令时,用BASH代替CSH

php - Symfony2 - 一条 route 的多个 slug

Bash 字符类参数扩展不一致行为

linux - 在 Bash 中,有没有办法用双引号将变量展开两次?