简体   繁体   English

如何得到没有。 与文件夹中所有文件中的字符串匹配的行数

[英]How to get no. of lines count that matches a string from all the files in a folder

Problem Description:- I have a folder which contains so many text files.问题描述:-我有一个包含很多文本文件的文件夹。 I want to search for a particular string say "string_example" in all files in that folder.Then I should get the count of total no.我想在该文件夹中的所有文件中搜索一个特定的字符串,比如“string_example”。然后我应该得到总数。 of lines in all files which has the string "string_example".具有字符串“string_example”的所有文件中的行数。 That means if there are 5 matching lines in 1st text file,10 matching lines in second text file, 3 matching lines in 3rd text file.Then the output should be 5+10+3=18这意味着如果第一个文本文件中有 5 个匹配行,第二个文本文件中有 10 个匹配行,第三个文本文件中有 3 个匹配行。那么输出应该是 5+10+3=18

What I Have tried:- I have surfed through the internet and found some commands like我尝试过的: -我已经通过互联网冲浪并找到了一些命令,例如

  • grep -r -n ".string_example" .

This bash command will print the file name along with line number of the lines which contains the string "string_example".Here is the sample output for better understanding此 bash 命令将打印文件名以及包含字符串“string_example”的行的行号。为了更好地理解,这里是示例输出

1st file:1:string_example is there第一个文件:1:string_example 在那里

1st file:2:string_example is not there第一个文件:2:string_example 不存在

2nd file:1:string_example is there第二个文件:1:string_example 在那里

etc.......But the actaul output I want is 3 from the above output.等等......但我想要的实际输出是上述输出中的 3。

I have also tried few more bash commands but of no use.我还尝试了更多的 bash 命令,但没有用。

My Question :- Is there any bash command for this kind of purpose.If not how to write a script for the following requirement.我的问题:- 是否有任何用于此类目的的 bash 命令。如果没有,如何为以下要求编写脚本。

Pls help me请帮助我

您可以使用wc -l您的grep以获取包含您的关键字的行数:

grep -r "string_example" . | wc -l

You could also use awk to do this:你也可以使用 awk 来做到这一点:

awk '/string_example/{++c}END{print c}' *

c is incremented every time a line matches the pattern.每当一行与模式匹配时, c就会增加。 Once all files have been read, print the total count.读取所有文件后,打印总计数。

You want something like this?你想要这样的东西吗?

grep -l string_example *|xargs wc -l

Edit:编辑:
You want to get numer of lines that matched in all files, or total numer of lines in files that contains matched line?您想获取所有文件中匹配的行数,或包含匹配行的文件中的总行数?

With this command given at the shell prompt you'll使用在 shell 提示符下给出的这个命令,你将

% find -type f -name \*.h | xargs grep -l stdlib  | xargs wc -l | awk '{a+=$1} END{print a}'
16372
% 
  1. get a list of all files, here and under, ending in .h获取所有文件的列表,这里和下面,以.h
  2. grep these files to find references to stdlib and by the option -l print only (and once) the names of the files that have at least one match grep 这些文件以查找对stdlib引用,并通过选项-l仅打印(并且一次)具有至少一个匹配项的文件的名称
  3. pass the list of names to wc -l将名称列表传递给wc -l
  4. use awk to sum the count of lines for each file使用awk对每个文件的行数求和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM