V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
0x47
V2EX  ›  程序员

怎么用命令行抽出一个文件的每一行,过滤出 ID,然后对每个调用 curl?

  •  
  •   0x47 · 2021-03-23 18:44:17 +08:00 · 1567 次点击
    这是一个创建于 1101 天前的主题,其中的信息可能已经有所发展或是发生改变。

    场景是这样的:有一个 log 文件,里面每一行都是类似 xxxxid=12345xxxx,x 是其他字符。我要从每一行里抽出 id,然后调用 API 。

    我现在的做法是,先cat file | xargs -n1 -I {} sh -c "echo {} | grep -o -E id=[0-9]* | grep -o -E [0-9]*",把所有 id 逐行打印出来后、手动保存成另一个文件 file2 。

    接着cat file2 | xargs -n1 -I{} sh -c "curl example.com/is/{} | grep -E 'id|status',打印所有调用 API 的结果。

    有啥简单的方法,一行可以搞定的么?环境受限,只能用命令行工具。

    8 条回复    2021-03-24 17:13:28 +08:00
    Cooky
        1
    Cooky  
       2021-03-23 18:47:52 +08:00 via Android
    cat | sed | xargs
    PTLin
        2
    PTLin  
       2021-03-23 19:37:01 +08:00
    ```
    for i (`cat foo.txt`) {echo $i|rg -o '.*id=(.*)' -r '$1' >> out.txt}
    ```
    这个是 zsh 配上 ripgrep 实现的
    IgniteWhite
        3
    IgniteWhite  
       2021-03-23 20:43:01 +08:00 via iPhone
    awk 最适合
    lizliz
        4
    lizliz  
       2021-03-23 22:24:18 +08:00
    perl -lane 'if(/AC=(\d+)/){system("curl www.baidu.com/$1");}'
    lizliz
        5
    lizliz  
       2021-03-23 22:35:43 +08:00
    awk '{a=gensub(/.*AC=([0-9]+).*/,"\\1","g");print "curl www.xxx/" a}' xx.file |sh

    awk 也行哈,不过一般 linux 都有 perl
    huangmingyou
        6
    huangmingyou  
       2021-03-24 10:26:39 +08:00
    我一般习惯 awk , xargs 不太好用。
    rizon
        7
    rizon  
       2021-03-24 10:58:25 +08:00
    如果条数不多(看电脑性能千行估计也没啥问题)

    Change/Select All Occurrences
    很多工具都有类似功能 多行编辑,配合 单词跳转光标。
    几秒钟搞定的事。

    ---

    如果连工具也没有,用我的在线笔记工具 notelive.cc
    也有这个功能,文本编辑框 鼠标邮件就看到了。
    omph
        8
    omph  
       2021-03-24 17:13:28 +08:00
    grep -oP '(?<=id=)[0-9]+' file.log | while read -r id; do curl "example.com/$id"; done
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5844 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 06:18 · PVG 14:18 · LAX 23:18 · JFK 02:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.