V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
hailongs
V2EX  ›  Linux

请教 shell 的朋友帮忙处理个字符串

  •  
  •   hailongs · 2016-11-02 16:05:58 +08:00 · 2116 次点击
    这是一个创建于 2703 天前的主题,其中的信息可能已经有所发展或是发生改变。

    ......&key=xxxxx&name=..........

    有很多这样的行,我想用 shell 取到 key=xxxxx ,其他的多余字段不要。怎么操作。

    xxxxx 是变量,每行都不同。谢谢!

    6 条回复    2016-11-03 09:37:25 +08:00
    giskard
        1
    giskard  
       2016-11-02 16:13:27 +08:00
    cut -d '&' -f2 xxx
    xxx 是你的文件名,-d '&' 表示以 '&' 作为字段分隔符,-f2 表示取第二个字段
    rrfeng
        2
    rrfeng  
       2016-11-02 16:14:07 +08:00
    grep -Po 'key=[^&]*'
    hailongs
        3
    hailongs  
    OP
       2016-11-02 16:28:11 +08:00
    @rrfeng 感谢。
    SoloCompany
        4
    SoloCompany  
       2016-11-02 23:42:31 +08:00
    -P 不是所有 grep 都支持的吧,比如 macOS 就不支持
    用 grep -o '&key=[^&]*' | cut -c5- 就好了
    yuedingwangji
        5
    yuedingwangji  
       2016-11-03 00:27:19 +08:00
    grep -oP '(?<=&)key=.*(?=&)'
    uuspider
        6
    uuspider  
       2016-11-03 09:37:25 +08:00 via iPhone
    tr '&' '\n' | grep 'key='
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3534 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 04:51 · PVG 12:51 · LAX 21:51 · JFK 00:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.