我想用来grep
在第二个文件中搜索一个文件中的模式。我的模式文件是这样的:
K02217
K07448
KO8980
要搜索的文件是:
>aai:AARI_24510 proP; proline/betaine transporter; K03762 MFS transporter, MHS family, proline/betaine transporter
>aai:AARI_26600 ferritin-like protein; K02217 ferritin [EC:1.16.3.1]
>aai:AARI_28260 hypothetical protein
>aai:AARI_29060 ABC drug resistance transporter, inner membrane subunit; K09686 antibiotic transport system permease protein
>aai:AARI_29070 ABC drug resistance transporter, ATP-binding subunit (EC:3.6.3.-); K09687 antibiotic transport system ATP-binding protein
>aai:AARI_29650 hypothetical protein
>aai:AARI_32480 iron-siderophore ABC transporter ATP-binding subunit (EC:3.6.3.-); K02013 iron complex transport system ATP-binding protein [EC:3.6.3.34]
>aai:AARI_33320 mrr; restriction system protein Mrr; K07448 restriction system protein
我尝试的命令是:
fgrep --file=pattern.txt file.txt >> output.txt
这将打印 file.txt 中找到模式的行。我需要它来打印一列包含找到的模式的列。所以像这样:
K07448 mrr; restriction system protein Mrr; K07448 restriction system
K02217 ferritin-like protein; K02217 ferritin [EC:1.16.3.1]
任何人都可以建议我该怎么做?
答案1
如果您不介意其中有一个额外的列,您可以使用join
和grep
来执行此操作。
$ join <(grep -of patterns.txt file.txt | nl) \
<(grep -f patterns.txt file.txt | nl)
1 KO3322 proteinaseK (KO3322)
2 KO3435 Xxxxx KO3435;folding factor
3 KO3435 Yyyyy KO3435,xxxx
答案2
您可以使用 shell 循环:
$ while read pat; do
grep "$pat" file |
while read match do
echo -e "$pat\t$match"
done
done < patterns
KO3435 Xxxxx KO3435;folding factor
KO3435 Yyyyy KO3435,xxxx
KO3322 proteinaseK (KO3322)
我通过在 UniProt 人类平面文件 (625M) 上运行它并使用 1000 个 UniProt ID 作为模式进行测试。在我的 Pentium i7 笔记本电脑上大约需要 6 分钟。当我只查找 100 个模式时,大约花了 35 秒。
正如下面的评论中所指出的,您可以通过跳过echo
和 使用grep
和--label
选项来稍微加快速度-H
:
$ while read pat; do
grep "$pat" --label="$pat" -H < file
done < patterns
在示例文件上运行此命令会产生:
$ while read pat; do
grep "$pat" --label="$pat" -H < kegg.annotations;
done < allKO.IDs.txt > test1
terdon@oregano foo $ cat test1
K02217:>aai:AARI_26600 ferritin-like protein; K02217 ferritin [EC:1.16.3.1]
K07448:>aai:AARI_33320 mrr; restriction system protein Mrr; K07448 restriction system protein
答案3
您可以使用确认:
$ ack "$(tr '\n' '|' < pattern.txt | sed -e 's/.$//')" --print0 --output='$& $_' file.txt
KO3322 proteinaseK (KO3322)
KO3435 Xxxxx KO3435;folding factor
KO3435 Yyyyy KO3435,xxxx