doe*_*247 5 grep regular-expression
我想找到包含任何单词的行三遍。为此,我认为最好使用该grep
命令。
这是我的尝试。
grep '\(.*\)\{3\}' myfile.txt
Run Code Online (Sandbox Code Playgroud)
Qua*_*odo 13
使用标准词定义,
GNU Grep,任何单词出现3 次或更多次。
grep -E '(\W|^)(\w+)\W(.*\<\2\>){2}' file
Run Code Online (Sandbox Code Playgroud)
GNU Grep,任何单词仅出现3次。
grep -E '(\W|^)(\w+)\W(.*\<\2\>){2}' file | grep -Ev '(\W|^)(\w+)\W(.*\<\2\>){3}'
Run Code Online (Sandbox Code Playgroud)
POSIX awk中,只有3出现次数的任何单词。
grep -E '(\W|^)(\w+)\W(.*\<\2\>){2}' file
Run Code Online (Sandbox Code Playgroud)
对于3 次或更多出现,只需更改==
为>=
。
等效高尔夫球单线:
awk -F '[^_[:alnum:]]+' '{split("",c);for(i=1;i<=NF;i++)c[$i]++;for(i in c)if(c[i]==3){print;next;}}' file
Run Code Online (Sandbox Code Playgroud)
GNU Awk,这个词ab
只出现了 3 次。
gawk 'gsub(/\<ab\>/,"&")==3' file
Run Code Online (Sandbox Code Playgroud)
对于3 次或更多出现,只需更改==
为>=
。
阅读材料
\2
是一个反向引用。\w
\W
\<
\>
GNU Grep 中的特殊表达式。[:alnum:]
POSIX字符类。像这样?
egrep '(\<.+\>).+\<\1\>.+\<\1\>'
Run Code Online (Sandbox Code Playgroud)
egrep
(或grep -E
)启用反向引用所需的扩展正则表达式\<.+\>
将匹配至少 1 个字符的任何单词
\<
resp\>
匹配单词边界(在您的尝试中,您根本没有考虑单词边界).+
匹配一个或多个字符的序列(在您的尝试中,您使用.*
了匹配零个或多个字符的序列!)\1
) 和第三次 (\1
再次)。
.+
匹配之间有一个或多个字符 ( ) 的任何序列,因此“foo bar foo dorbs foo godly”将匹配(单词“foo”出现 3 次)。[[:space:]]+
。