如何使用grep从文件中遍历模式 [英] how to loop over pattern from a file with grep

查看:93
本文介绍了如何使用grep从文件中遍历模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在文本文件(list.txt)中grep一系列模式,每行一个,以查找目标文件(file1)中每个模式有多少匹配。目标文件如下所示:

I am trying to grep a series of patterns that are, one per line, in a text file (list.txt), to find how many matches there are of each pattern in the target file (file1). The target file looks like this:

$ cat file1

2346 TGCA
2346 TGCA
7721 GTAC
7721 GTAC
7721 CTAC

我需要每个数值模式的计数(2346和2271)。

And I need counts of each numerical pattern (2346 and 2271).

如果您在引号中提供模式列表,我有这个脚本可行:

I have this script that works if you provide a list of the patterns in quotes:

 $ for p in '7721' '2346'; do   printf '%s = ' "$p"; grep -c "$p" file1; done

 7721 = 3
 2346 = 2

想要做的就是搜索list.txt中的所有模式:

What I would like to do is search for all patterns in list.txt:

$ cat list.txt

7721
2346
6555
25425
22
125
....
19222

如何转换我的脚本以查看list.txt并搜索每个模式,并返回与上面相同的输出(pattern = count )例如:

How can I convert my script above to look in the list.txt and search for each pattern, and return the same output as above (pattern = count) e.g.:

2346 = 2
7721 = 3
....
19222 = 6


推荐答案

试试这个awk oneliner:

try this awk oneliner:

 awk 'NR==FNR{p[$0];next}$1 in p{p[$1]++}END{for(x in p)print x, p[x]}' list.txt file

这篇关于如何使用grep从文件中遍历模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆