简体   繁体   English

Linux->终端命令-> Grep->与符号有关的表达式/异常

[英]Linux -> Terminal command -> Grep -> Expressions / Exceptions related to symbol

Simply: I have problem with command which should print me lines containing any of those two expressions: " king" , "king's son" . 简而言之:我的命令有问题,该命令应该向我显示包含以下两个表达式之一的行:“ king”“ king's son” This is where I got so far: 这是我到目前为止的去处:

grep -w "king's son\|king" frog.txt

It does work but it include "king's" which should not happen. 它确实有效,但是它包含不应发生的“国王”

Adding -v grep "king's" does not work as it deletes "king's son" also. 添加-v grep "king's"不起作用,因为它也会删除“ king's son”

I am using Ubuntu 32 bit system installed on Virtual Box Machine. 我正在使用Virtual Box Machine上安装的Ubuntu 32位系统。

-w won't help much because king is considered a word in king's as ' is a non-word character. -w也不会有多大效果,因为king是在考虑一个字king's'是一个非字字符。

Use: 采用:

grep -E "([[:space:]]|^)king('s son)?([[:space:]]|$)" frog.txt

Or using lookarounds if your grep has PCRE option available: 或者,如果您的grep具有可用的PCRE选项,则使用环视方法

grep -P "(?<=[[:space:]]|^)king('s son)?(?=[[:space:]]|$)" frog.txt
grep -E "([[:space:]]|^)king('s son)?([[:space:]]|$)" frog.txt

For example, if frog.txt contains 例如,如果frog.txt包含

kingb    # no match
king's   # no match
king-bee # no match 
breaking # no match
king's hello # no match
king's sonth # no match

king     # match
a king bee  # match
king    bee # match (with a TAB)
king's son  # match

then the above command returns 然后上面的命令返回

king     # match
a king bee  # match
king    bee # match (with a TAB)
king's son  # match

This oughta do it: 这应该做到:

grep -E "(^|[ \t])(king|king's son)([ \t]|$)" frog.txt

It uses the groups (^|[ \\t]) and ([ \\t]|$) to match word separators or the beginning/end of lines. 它使用组(^|[ \\t])([ \\t]|$)来匹配单词分隔符或行的开头/结尾。

grep -w "king's son\|king$" frog.txt

the following line maybe work for your situation. 以下几行可能适合您的情况。

grep -w "king's son\|king$\|king\ " frog.txt

the result is : 结果是:

king's son   #match
king         #match
king's hello #not match

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM