gpt4 book ai didi

awk - 使用grep或awk匹配文本

转载 作者:行者123 更新时间:2023-12-02 22:59:59 25 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作为子字符串,则这可能会产生误报。您可以使用 grep即时为 sed构建更确定的模式:

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/

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