IT序号网

regex之使用正则表达式修剪URL

zhenyulu 2025年12月25日 编程语言 160 0

我有一个文本文件,该文件遵循以下格式:

http://www.mywebsite.com/user1242/random-information 
http://www.mywebsite.com/otheruser/writing-other-stuff 
http://www.mywebsite.com/anotheruser/fwefawef-wfefwef 
http://www.mywebsite.com/testuser/fwefweaf-fawefw 
http://www.mywebsite.com/testing123/this-is-a-test 

我要修剪最后一部分并使列表看起来像这样:
http://www.mywebsite.com/user1242 
http://www.mywebsite.com/otheruser 
http://www.mywebsite.com/anotheruser 
http://www.mywebsite.com/testuser 
http://www.mywebsite.com/testing123 

这可能与正则表达式有关吗,还是我应该寻找其他方式来做到这一点?

我希望通过命令行来实现,但是如果这样更容易的话,我可以通过NotePad ++之类的工具来运行它。

请您参考如下方法:

使用awk:

awk 'BEGIN{FS=OFS="/"} {$NF=""; print substr($0, 1, length($0)-1)}' file 
http://www.mywebsite.com/user1242 
http://www.mywebsite.com/otheruser 
http://www.mywebsite.com/anotheruser 
http://www.mywebsite.com/testuser 
http://www.mywebsite.com/testing123 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!