我想在 100 个文件中搜索 14 种不同的模式。目前我尝试过的
cat s_3_2_*_qseq.txt | grep -c 'pattern1\|pattern2\|pattern3\|pattern4\|pattern5\|...pattern14'
这给了我每个文件中所有模式的编号
s_3_3_001_qseq.txt:12
s_3_3_002_qseq.txt:15
.
s_3_3_0068_qseq.txt:5
我有兴趣分别查看每种模式的结果,如下所示:
file pattern1 pattern2 ..... pattern14
s_3_3_001_qseq.txt: 0 2 5
s_3_3_002_qseq.txt: 7 1 3
.
.
s_3_3_0068_qseq.txt: 1 2 1
任何想法我该怎么做,unix、perl 或 python 解决方案都会很好。
答案1
awk 解决方案 - 代码可以整理或缩短 - 我确信
$ cat file1
pat1
pat2
pat1
$ cat file2
pat2
pat2
pat1
$ awk -f 1.awk file1 file2
file pat1 pat2
file1 2 1
file2 1 2
$ cat 1.awk
BEGIN{
pat["pat1"]="pat1";
pat["pat2"]="pat2";
file["file1"]="file1";
file["file2"]="file2"
}
{
for (i in pat) {
if ($0 ~ i) pat_count[FILENAME,i]++
}
}
END {
printf("file\t\t")
for(i in pat) {
printf("%s\t\t",i)
}
printf("\n")
for (i in file) {
printf("%s\t\t",i)
for(j in pat) {
printf("%d\t\t", pat_count[i,j])
} ; printf("\n")
}
}
答案2
使用awk:
在称为搜索的逗号分隔变量中提供搜索词。
$ cat a
alice
bob
john
$ cat b
alice
bob
$ cat c
alice
$ cat search-count.awk
BEGIN {
# read search terms
split(search, searches, /,/)
delim=":"
# fill initially zero count for all searches
for (f = 1; f < ARGC; f++)
for (s in searches)
matches[searches[s],delim,ARGV[f]] = 0
}
{
for (s in searches) {
if ($0 ~ searches[s]) {
matches[searches[s],delim,FILENAME]++
}
}
}
END {
# print header
printf "FILE"
for (s in searches) {
printf "\t%s", searches[s]
}
printf "\n"
# print counts
for (f = 1; f < ARGC; f++) {
printf ARGV[f]
for (s in searches) {
printf "\t%s", matches[searches[s],delim,ARGV[f]]
}
printf "\n"
}
}
$ awk -v search="alice,bob,john" -f ./search-count.awk a b c
FILE alice bob john
a 2 2 0
b 1 1 0
c 0 2 0
答案3
PATTERNS=(dummy pattern1 pattern2 ... pattern14) ; dummy to occupy index zero
for file in /path/to/my/files/*
do
for p in 1 2 3 4 5 6 7 8 9 10 11 12 13 14
printf ${file}"\t"
do
c=$(grep -c PATTERNS[${p}] ${file}) # depending on the nature of your pattern you may need quotes around it
printf ${c}"\t"
done
echo
done
像这样的东西可能会起作用(未检查语法,如果您决定使用它,请小心)