【问题标题】:Parse a file to pull out 2 sets of information解析文件提取2组信息
【发布时间】:2013-08-17 00:06:31
【问题描述】:

我有一个记录用户输入的日志文件。日志中的每一行都是唯一的,我需要提取 2 个特定项目 - 一个 userId 和一个 URL。我不能只使用awk < file '{print$1, print$6}',因为这些项目并不总是在每一行中的相同位置。

示例文本:

userId='1' managed:no address:123street phone:1234567890 http:/someurl.com
newuser:yes userId='2' managed:yes address:123street  http:/someurl.com
userId='3' address:123 street phone:1234567890 http:/someurl.com
userId='4' managed:no address:123street phone:1234567890 http:/someurl.com

我需要将 userId 和 URL 地址解析为一个文件,但它们并不总是在每一行中的相同位置。任何建议将不胜感激。

【问题讨论】:

    标签: parsing unix awk


    【解决方案1】:
    $ awk '{for(i=1;$i!~/userId/;i++); print $i, $NF}' file
    userId='1' http:/someurl.com
    userId='2' http:/someurl.com
    userId='3' http:/someurl.com
    userId='4' http:/someurl.com
    

    【讨论】:

    • 谢谢。我希望我的超能力会随时发挥作用。
    【解决方案2】:

    试试下面的 代码:

    gawk '{
        for (i=1; i<=NF; i++)
            if ($i ~ "^userId=") id=gensub(/userId=\047([0-9]+)\047/, "\\1", "", $i)
            else if ($i ~ "^http") url=$i
            print "In line "NR", the id is "id" and the url is "url
    }' file.txt
    

    示例输入:

    userId='1' managed:no address:123street phone:1234567890 http:/someurl1.com
    newuser:yes userId='2' managed:yes address:123street  http:/someurl2.com
    userId='3' address:123 street phone:1234567890 http:/someurl3.com
    userId='4' managed:no address:123street phone:1234567890 http:/someurl4.com
    

    示例输出:

    In line 1, the id is 1 and the url is http:/someurl1.com
    In line 2, the id is 2 and the url is http:/someurl2.com
    In line 3, the id is 3 and the url is http:/someurl3.com
    In line 4, the id is 4 and the url is http:/someurl4.com
    

    此解决方案的优势在于将 id 或 http 项放在您想要的任何位置。

    【讨论】:

    • 更新为使用 gawk 和捕获组显示不带单引号的整数。
    【解决方案3】:

    awk:

    awk '{for(c=1;c<NF;c++){if(match($c,/userId/)){print $c,$NF; break}}}' your.file
    

    输出:

    userId='1' http:/someurl.com
    userId='2' http:/someurl.com
    userId='3' http:/someurl.com
    userId='4' http:/someurl.com
    

    【讨论】:

    • 我在这里遗漏了一些东西。此命令不返回任何行,您如何获得“http”结果?谢谢。
    • 我已经用您发布的数据对其进行了测试。我发布的输出来自我的测试运行。 http url 始终是您输入的最后一列,这就是为什么$NF(NF 是 awk 中每行计数的字段)
    猜你喜欢
    • 2015-06-07
    • 2015-04-19
    • 2020-07-21
    • 2020-12-28
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    相关资源
    最近更新 更多