开发者

Remove text after last /

I have list of links like:

http://site1.com/lalala.html
http://site2.com/lalala/

And I need to remove all text in row after last / How could I do it using awk or sed? Or maybe some perl or python script? T开发者_如何转开发hanks for help!


This could work:

$ echo http://site1.com/lalala/ | sed -e 's;\(.*/\).*;\1;'
http://site1.com/lalala/
$ echo http://site1.com/lalala/foo.html | sed -e 's;\(.*/\).*;\1;'
http://site1.com/lalala/


In PHP, you'd use dirname() on the string. Is PHP one of the possible scripting language?

EDIT:

Perl and Python both have dirname(), am not so sure of the implementation. Sorry


Aside from the language used, I would split all lines (with \n as separator) to an array, then I would perform a search for the lastIndexOf "/" of each element, then I would remove the part I don't need using regular String methods. For sure you can do something interesting with RegExp too.


You can use

sed -e 's/\(.*\)\/[^\/]*/\1/g'

Examples:

bash-$ echo "http://site1.com/lalala.html" |sed -e 's/\(.*\)\/[^\/]*/\1/g'
http://site1.com
bash-$ echo "http://site2.com/lalala/" |sed -e 's/\(.*\)\/[^\/]*/\1/g'
http://site2.com/lalala


Using awk you can use:

awk 'BEGIN { FS="/"; OFS="/"; } { $NF = ""; print; }'

Examples:

$ echo http://site1.com/lala/la.txt | awk 'BEGIN { FS="/"; OFS="/"; } { $NF = ""; print; }'
http://site1.com/lala/

$ echo http://site1.com/lala/ | awk 'BEGIN { FS="/"; OFS="/"; } { $NF = ""; print; }'
http://site1.com/lala/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜