关于'grep -f':使用文件匹配模式 [英] About 'grep -f': match pattern with file

查看:160
本文介绍了关于'grep -f':使用文件匹配模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 grep -f 函数从文件中提取符合特定模式的行。假设我的模式文件是 pattern.txt ,如下所示。

  1 
2
3
4
5

我匹配这个模式的文件是 file.txt

  1 :: anv 
2 :: tyr
3 :: yui
4 :: fng
5 :: gdg
6 :: ere
7 :: rer
8 :: 3rr
9 :: gty

现在当我做一个grep -f pattern.txt file.txt时,我得到了这个 - >

  1 :: anv 
2 :: tyr
3 :: yui
4 :: fng
5 :: gdg
8 :: 3rr

上面的输出中的最后一行导致我的问题。如何修改这个grep命令以得到如下输出(显示正确的对应关系)?

  1 :: anv 
2 :: tyr
3 :: yui
4 :: fng
5 :: gdg


解决方案

在模式之前添加 ^ 以使 grep 将匹配你的模式的一行开始。如果你的模式实际上是一组数字,你不需要模式列表。只需使用 ^ [1-5]:


I am using the grep -f function to extract lines from a file which match a particular pattern. Let's say my pattern file is pattern.txt, as follows.

1
2
3
4
5

And the file against which I am matching this pattern is file.txt,

1::anv
2::tyr
3::yui
4::fng
5::gdg
6::ere
7::rer
8::3rr
9::gty

Now when I do a grep -f pattern.txt file.txt, I am getting this ->

1::anv
2::tyr
3::yui
4::fng
5::gdg
8::3rr

The last line in the output above, is causing my problem. How do I modify this grep command so as to get the output (showing correct correspondences) as follows?

1::anv
2::tyr
3::yui
4::fng
5::gdg

解决方案

Add ^ before your patterns so that grep will match a line start with your pattern. If your pattern is actually set of numbers, You don't need a list of patterns. Just use ^[1-5]:.

这篇关于关于'grep -f':使用文件匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆