我想使用我的id_file来搜索我的big_file,提取与行的开头匹配的行大文件。
我是一名初学者,正在努力使用 grep(版本 grep (BSD grep) 2.5.1-FreeBSD
)并理解下面引用的解决方案。
我的 id_file
包含 id:
67b
84D
118
136
166
我的big_file
看起来像这样:
118 ABL1_BCR
118 AC005258
166 HSP90AB1
166 IKZF2_SP
166 IL1RAP_D
136 ABL1_BCR
136 ABL1_BCR
555 BCR_136
555 BCR_136
555 BCR_136
59 UNC45B_M 166
59 WASF2_GN 166
59 YPEL5_CX 166
根据 Chris Seymour 的建议 here
尝试 1:我使用
grep -wFf id_file big_file
这显然不起作用,因为数字出现在 big_file
行的其他位置。
尝试 2:我修改了 id_file;
^67b
^84D
^118
^136
^166
并再次运行grep -wFf id_file big_file
。
当然,这也行不通
我看了巴蒂玛的镜头here但我未能实现该建议。
Better usage is taking only some patterns from some file and this patterns use for your file
grep '^PAT' patterns.txt | grep -f - myfile
This will take all patterns from file patterns.txt starting with PAT and use this patterns from the next grep to search in myfile.
我尝试以多种方式用我的示例重现上面的代码,但显然我只是不明白他们的意思,因为它们都不起作用。
我的修改 1 有 2 个结果:没有这样的文件或目录
或根本没有输出。
有没有办法只用 grep 来做到这一点?
如果有人能够为我分解它,我将不胜感激。
最佳答案
这似乎是 BSD grep
的问题。看
https://unix.stackexchange.com/questions/352977/why-does-this-bsd-grep-result-differ-from-gnu-grep对于类似的问题。
您可以使用 awk
作为替代方案(可能在某个地方有重复的解决方案):
awk 'NR==FNR{a[$1]; next} $1 in a' id_file large_file
NR==FNR{a[$1]; next}
使用id_file
的第一个字段作为键构建关联数组
如果 $1 in a
将为 true。如果是这样,将打印整行。
large_file
中的一行的第一个字段与数组 a
中的任何键匹配,关于grep - 如何将行的开头与 id 文件中的模式相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68406907/