【问题标题】:How to obtain the query order output when we use grep?使用 grep 时如何获取查询订单输出?
【发布时间】:2020-01-24 08:26:52
【问题描述】:

我有 2 个文件 文件1.txt

1
3
5
2

文件2.txt

1 aaa
2 bbb
3 ccc
4 aaa
5 bbb

期望的输出:

1 aaa
3 ccc
5 bbb
2 bbb

使用的命令:cat File1.txt |grep -wf- File2.txt,但输出为:

1 aaa
2 bbb
3 ccc
5 bbb

是按查询顺序返回输出的一种方式吗? 提前谢谢!!!

【问题讨论】:

    标签: linux grep output


    【解决方案1】:

    重要修改

    再三考虑,不要将 grep 与重定向一起使用,因为它非常慢。使用 awk 读取原始模式以获取订单。

    改用这个

    grep -f patterns searchdata | awk 'NR==FNR { line[$1] = $0; next } $1 in line { print line[$1] }' - patterns > matched
    

    基准测试

    #!/bin/bash
    paste <(shuf -i 1-10000) <(crunch 4 4 2>/dev/null | shuf -n 10000) > searchdata
    shuf -i 1-10000 > patterns
    
    printf 'Testing awk:'
    time grep -f patterns searchdata | awk 'NR==FNR { line[$1] = $0; next } $1 in line { print line[$1] }' - patterns > matched
    wc -l matched
    
    cat /dev/null > matched
    
    printf '\nTesting grep with redirection:'
    time {
        while read -r pat; do
            grep -w "$pat" searchdata >> matched
        done < patterns
    }
    wc -l matched
    

    输出

    Testing awk:
    real    0m0.022s
    user    0m0.017s
    sys 0m0.010s
    10000 matched
    
    Testing grep with redirection:
    real    0m36.370s
    user    0m28.761s
    sys 0m7.909s
    10000 matched
    

    原创

    要保留查询顺序,请逐行读取文件:

    while read -r pat; do grep -w "$pat" file2.txt; done < file1.txt
    

    我不认为 grep 有支持此功能的选项,但如果您要读取大文件,此解决方案会更慢。

    【讨论】:

    • 完美运行!!!!我正在努力弄清楚它是如何工作的。事实上 grep 手册并没有提到这方面的内容,也没有为此目的提供任何选择。
    • 我做了一些基准测试,它比我想象的还要慢。更新版本更快。
    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多