【问题标题】:Count the occurrence of a pattern from a column of one file in other file从另一个文件的一个文件的列中计算模式的出现次数
【发布时间】:2020-05-14 11:04:43
【问题描述】:

我创建了一个包含一列模式列表的文件(总共 2,196 个),我想在其他文本文件中找到这些模式列表,该文件大约有 4 亿行。 例如:

file1

abc1
abc2
abc3
abc4
abc5

file2

abc1
abc1
abc1
abc1
abc1
abc2
abc2
abc2
abc2

想要的输出:

文件3

abc1    5
abc2    2

我可以用 awk 或 grep 来一一做:

awk '/abc1/{++c}END{print c}' file1 | wc -l > file3

grep 'abc1' file1 | wc -l > file3

但是,当我尝试时:

cat file1 | xargs -L 1 grep file2 | wc -l > file3

我收到一条错误消息:

grep: abc1: No such file or directory
grep: abc2: No such file or directory
etc

我试过了:

cat file1 | xargs -L 1 grep '' file2 | wc -l > file3

也不行!那么我做错了什么?

谢谢!

【问题讨论】:

    标签: file awk grep


    【解决方案1】:

    您的cat file1 | xargs -L 1 grep file2… 正在尝试从不存在的文件abcXgrep 模式file2。你可以从类似的东西开始

    <file1 xargs -I{} grep "{}" file2
    

    并将其扩展到

    $ <file1 xargs -I{} sh -c 'printf "%s\t%s\n" "{}" $(grep -c "{}" file2)'
    abc1    5
    abc2    4
    abc3    0
    abc4    0
    abc5    0
    

    但这对于大型模式文件来说效率不高。


    使用grepsortuniq

    $ grep -F -x -f file1 file2  | sort | uniq -c > file3
    

    输出file3:

          5 abc1
          4 abc2
    

    如果需要反转匹配数和模式:

    grep -F -x -f file1 file2  | sort | uniq -c | awk '{ print $2"\t"$1 }' > file3
    

    输出file3:

    abc1    5
    abc2    4
    

    使用awk:

    awk '
      NR==FNR{ a[$0] }
      NR!=FNR && $0 in a{ a[$0]++ }
      END{ for (i in a){ if (a[i])print i"\t"a[i] }}
    ' file1 file2 > file3
    

    输出file3:

    abc1    5
    abc2    4
    

    【讨论】:

      【解决方案2】:

      最简单的解决方案如下恕我直言。

      awk 'FNR==NR{a[$0]++;next} ($1 in a){print $1,a[$1]}' Input_file2  Input_file1
      

      说明:为上述代码添加说明。

      awk '                         ##Starting awk program from here.
      FNR==NR{                      ##Checking condition if FNR==NR which will be TRUE when Input_file2 is being read.
        a[$0]++                     ##Creating an array named a index is $0 and increment it with 1 each time it goes to line.
        next                        ##next will skip all further statements from here.
      }
      ($1 in a){                    ##Checking condition if $1 is present in array a then do following.
        print $1,a[$1]              ##Printing first field then value of array a with index $1.
      }
      ' Input_file2  Input_file1    ##Mentioning Input_file names here.
      

      输出如下。

      abc1 5
      abc2 4
      

      【讨论】:

        猜你喜欢
        • 2021-02-19
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 2017-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多