【问题标题】:Finding the frequency of an expression in all files of a directory在目录的所有文件中查找表达式的频率
【发布时间】:2012-08-03 07:41:46
【问题描述】:

我正在尝试编写一个 shell 脚本,该脚本将在当前目录中的每个文件中搜索正则表达式,而不使用临时文件。

最初,我使用一个临时文件来存储echo * | sed 's/ /\n/g',然后循环遍历该文件的每一行,在每一行上使用cat,然后grepping我的表达式并计算输出的行数。我在搜索临时文件时遇到了一些问题,想知道是否可以使用变量或一些非临时文件方法来完成所有工作(我也不想为临时文件创建单独的目录)。

我在使用变量时遇到的问题是,在我将变量的值设置为echo * | sed 's/ /\n/g' 的输出后,我不知道如何遍历每一行,以便从文件中获取表达式计数.

我只希望以下工作(我对表达式进行硬编码):

% ls
% file1 file2 file3
% ./countMost.sh
% file2(28)
% ls
% file1 file2 file3

表示 file2 具有最多的表达式实例(其中 28 个)。

【问题讨论】:

    标签: regex shell unix


    【解决方案1】:

    你可以试试这样的:

    grep -c regex files | sed -e 's/^\(.*\):\(.*\)$/\2 \1/' | sort -r -n | head -n 1
    

    regex 是您的正则表达式(也可以使用 egrep),files 是您的文件列表。

    给定 3 个文件:

    file1:
    qwe
    qwe
    qwe
    asd
    zxc
    
    file2:
    qwe
    asd
    zxc
    
    file3:
    asd
    qwe
    qwe
    qwe
    qwe
    

    然后我跑:

    grep -c 'qwe' file[1-3] | sed -e 's/^\(.*\):\(.*\)$/\2 \1/' | sort -r -n
    

    我得到了输出:

    4 file3
    3 file1
    1 file2
    

    此外,在末尾添加 | head -n 1 只会给我:

    4 file3
    

    【讨论】:

      【解决方案2】:

      类似版本的 Job Lin 解决方案使用 sort args 而不是 sed:

      grep -c -e "^d" file* | sort -n -k2 -t: -r |head -1
      

      (这里我寻找以“d”开头的行)

      【讨论】:

        【解决方案3】:

        这应该为您提供前十个最常见的小写单词(您将正则表达式更改为任何内容)在名为 test with counts 的目录中的一堆文件中。

        grep -rhoE "[a-z]+" test | sort | uniq -c | sort -r | head
              3 test
              2 wow
              2 what
              2 oh
              2 foo
              2 bar
              1 ham
        

        如果要按文件名计数,则删除 grep 上的 h 标志

          grep -roE "[a-z]+" test | sort | uniq -c | sort -r | head
              3 test/2:test
              1 test/2:wow
              1 test/2:what
              1 test/2:oh
              1 test/2:foo
              1 test/2:bar
              1 test/1:wow
              1 test/1:what
              1 test/1:oh
              1 test/1:ham
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-16
          • 2013-08-07
          • 1970-01-01
          • 1970-01-01
          • 2013-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多