简体   繁体   English

使用sed和regex捕获url的最后一部分

[英]Using sed and regex to capture last part of url

I'm trying to make sed match the last part of a url and output just that. 我正在尝试将sed匹配到url的最后一部分并输出。 For example: 例如:

echo "http://randomurl/suburl/file.mp3" | sed (expression)

should give the output: 应该给出输出:

file.mp3

So far I've tried sed 's|\\([^/]+mp3\\)$|\\1|g' but it just outputs the whole url. 到目前为止,我已经尝试了sed 's|\\([^/]+mp3\\)$|\\1|g'但它只输出整个网址。 Maybe there's something I'm not seeing here but anyways, help would be much appreciated! 也许有一些我在这里看不到的东西,但无论如何,帮助将不胜感激!

这工作:

 echo "http://randomurl/suburl/file.mp3" | sed 's#.*/##'

basename is your good friend. basename是你的好朋友。

> basename "http://randomurl/suburl/file.mp3"
=> file.mp3

This should do the job: 这应该做的工作:

$ echo "http://randomurl/suburl/file.mp3" | sed -r 's|.*/(.*)$|\1|'
file.mp3

where: 哪里:

  • | has been used instead of / to separate the arguments of the s command. 已被用来代替/来分隔s命令的参数。
  • Everything is matched and replaced with whatever if found after the last / . 一切都匹配,并替换为最后/后发现的任何东西。

Edit: You could also use bash parameter substitution capabilities: 编辑:您还可以使用bash 参数替换功能:

$ url="http://randomurl/suburl/file.mp3"
$ echo ${url##*/}
file.mp3
echo 'http://randomurl/suburl/file.mp3' | grep -oP '[^/\n]+$'

这是使用grep的另一种解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM