gpt4 book ai didi

awk - 使用 grep 或 awk 匹配文本

转载 作者:行者123 更新时间:2023-12-02 22:59:59 26 4
gpt4 key购买 nike

我在使用 grep 和 awk 时遇到问题。我认为这是因为我的输入文件包含看起来像代码的文本。

输入文件包含 ID 名称,如下所示:

SNORD115-40
MIR432
RNU6-2

引用文件如下所示:

Ensembl Gene ID HGNC symbol
ENSG00000199537 SNORD115-40
ENSG00000207793 MIR432
ENSG00000266661
ENSG00000243133
ENSG00000207447 RNU6-2

我想将源文件中的 ID 名称与引用文件相匹配,并打印出相应的 ensg ID 号,以便输出文件如下所示:

ENSG00000199537 SNORD115-40
ENSG00000207793 MIR432
ENSG00000207447 RNU6-2

我尝试过这个循环:

exec < source.file
while read line
do
grep -w $line reference.file > outputfile
done

我还尝试过使用 awk 来处理引用文件

awk 'NF == 2 {print $0}' reference file
awk 'NF >2 {print $0}' reference file

但我只得到了 grep 的 ID 之一。

任何建议或更简单的方法都会很好。

最佳答案

$ fgrep -f source.file reference.file 
ENSG00000199537 SNORD115-40
ENSG00000207793 MIR432
ENSG00000207447 RNU6-2

fgrep 相当于 grep -F:

   -F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by
newlines, any of which is to be matched. (-F is specified by
POSIX.)

-f 选项用于从文件中获取PATTERN:

   -f FILE, --file=FILE
Obtain patterns from FILE, one per line. The empty file
contains zero patterns, and therefore matches nothing. (-f is
specified by POSIX.)

如注释中所述,如果 reference.file 中的 ID 包含 source.file 中的 ID 作为子字符串,则可能会产生误报。您可以使用 sed 即时构建更明确的 grep 模式:

grep -f <( sed 's/.*/ &$/' input.file) reference.file

但是这样模式会被解释为正则表达式,而不是固定字符串,这可能容易受到攻击(尽管如果 ID 仅包含字母数字字符,则可能没问题)。不过,更好的方法(感谢@sidharthcnadhan)是使用 -w 选项:

   -w, --word-regexp
Select only those lines containing matches that form whole
words. The test is that the matching substring must either be
at the beginning of the line, or preceded by a non-word
constituent character. Similarly, it must be either at the end
of the line or followed by a non-word constituent character.
Word-constituent characters are letters, digits, and the
underscore.

所以你的问题的最终答案是:

grep -Fwf source.file reference.file

关于awk - 使用 grep 或 awk 匹配文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16458074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com