【问题标题】:Using regex to trim URLs?使用正则表达式修剪 URL?
【发布时间】:2015-01-14 19:32:23
【问题描述】:

我有一个遵循这种格式的文本文件:

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++ 之类的东西来运行它......

【问题讨论】:

    标签: regex shell command-line ssh command


    【解决方案1】:
    awk NF-- FS=/ OFS=/
    

    结果

    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

    【讨论】:

    • NF-- 仅适用于 gnu-awk,不适用于其他 awk 版本,例如 OSX 上的 BSD awk
    【解决方案2】:

    使用 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
    

    【讨论】:

    • 工作完美!谢谢!我会在 8 分钟内接受答案!
    • 既然可以NF-- 和打印,为什么还要玩长度游戏?
    • @EtanReisner: NF-- 仅适用于 gnu-awk,它不适用于其他 awk,例如 OSX 上的 BSD awk
    【解决方案3】:

    试试这个:

    sed 's@/[^/]\+$@@g' file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多