url=http://www.foo.bar/file.ext; echo ${url##/*}
Run Code Online (Sandbox Code Playgroud)
我希望这段代码可以打印file.ext,但它打印了整个 URL。为什么?如何提取文件名?
Man*_*d3r 37
因为单词必须匹配要修剪的字符串。它应该看起来像:
$ url="http://www.foo.bar/file.ext"; echo "${url##*/}"
file.ext
Run Code Online (Sandbox Code Playgroud)
谢谢 derobert,你把我引向了正确的方向。此外,正如@frank-zdarsky 所提到的,basename它在 GNU coreutils 中,也应该在大多数平台上可用。
$ basename "http://www.foo.bar/file.ext"
file.ext
Run Code Online (Sandbox Code Playgroud)
der*_*ert 11
引用联机帮助页:
${parameter##word}
Remove matching prefix pattern. The word is expanded to produce
a pattern just as in pathname expansion. If the pattern matches
the beginning of the value of parameter, […]
Run Code Online (Sandbox Code Playgroud)
/*不匹配开头,因为您的 URL 以hnot开头/。
一个简单的方法来做你正在寻找的东西(根据你的评论)是echo "$url" | rev | cut -d / -f 1 | rev. 但是,当然,这将为以斜杠结尾的 URL 提供有趣的结果。
另一种做你想做的事情的方法可能是使用模式*/。
小智 9
basename(1) 也适用于 URL,因此您可以简单地执行以下操作:
url=http://www.foo.bar/file.ext; basename $url
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28541 次 |
| 最近记录: |