使用GREP -V排除字符串
我需要排除选定的字符串。我正在尝试使用grep -v
选项。
输入:
AM2RGHK
AM2RGHK-JO
AM2RGHK-FN
输出应为:
AM2RGHK-JO
AM2RGHK-FN
从输入列表中,如果我只想排除第一行,我正在使用grep -v am2rghk
但是我没有得到任何输出。 grep -v
在同一序列中排除所有字符串。有线索吗?
I have a requirement to exclude a selected string. I am trying to use grep -v
option.
Input:
AM2RGHK
AM2RGHK-JO
AM2RGHK-FN
Output should be:
AM2RGHK-JO
AM2RGHK-FN
From the input list, If I want to exclude only first line, I am using grep -v AM2RGHK
But I am not getting any output. grep -v
excludes all the strings in the same sequence. Any clue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
GREP
与所有输入行匹配,因为它的默认行为是匹配包含给定模式的行。它不必完全等于它。您可以告诉GREP,必须使用选项
-X
(- line-regexp
)找到确切的匹配。GREP -V -X AM2RGHK
执行您想要的工作。旁注:
由于您似乎不使用实际的正则拨号,但您只需要简单的文本匹配,因此您可以考虑选项
-f
(- filex-sinstrings
) 。它告诉grep
不要为模式中的任何字符赋予特殊意义。此外,将shell字符串包裹在
'''
中始终是一个好习惯。这样可以确保外壳不会尝试解释任何字符,例如空格。它可以使您感到很多头痛。结果命令将是:
grep
is matching all the input lines because it's default behavior is to match line that contains the given pattern. It doesn't have to be exactly equal to it.You can tell grep that it has to find an exact match by using the option
-x
(--line-regexp
).grep -v -x AM2RGHK
does what you want.Side notes:
Since you don't seem to use an actual regex but you just need simple text match, you may consider the option
-F
(--fixed-strings
). It tellsgrep
to not give special meaning to any character in the pattern.Moreover, it's always a good practice to encase shell strings in
''
. This ensures that the shell doesn't try to interpret any characters, like whitespaces. It can spare you a lot of headaches.The resulting command would be:
Input.txt:
标准输出:
input.txt:
standard output:
考虑一下您的控制权,在这种情况下,您可以与所讨论的字符串进行比较,但是我们可以在每一端添加一个垫子字符并查找它。
我们说的是,如果zam2rghkz!=电流然后打印它,则比较如下:
因此,输出变为:
注意:还有更多简洁的方法可以做到这一点,但这也是一个很好的方法。
Think about what you have control over, in this case you can compare against the string in question but instead of just the string we can add a pad character on each end and look for that.
This case we are saying if ZAM2RGHKZ != current then print it, the comparison would be as follows:
Hence the output becomes:
Note: there are more succinct ways to do this but this is a good way as well.
GREP有选项-x
例如:
grep has the option -x
for example: