Bash:如何为同一字符串的多个实例 grep 一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32761627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:37:49  来源:igfitidea点击:

Bash: How can I grep a line for multiple instances of the same string?

regexbashgrep

提问by BubbleMonster

I've got several lines that look like this:

我有几行看起来像这样:

aaaaaaaaxzaaaaaaaaaaaaaa
bbbbbbbbbbbbxzbbbbbbxzbb
ccxzcccccccccccccccccxzc
dddddddxzddddddddddddddd

Inside two of those lines, there are twoinstances of xzcharacters. I want grep to look for xztwice in the same line and output the lines that it matches on. If xzappears once, I don't want to know.

在其中两行中,有两个xz字符实例。我希望 grepxz在同一行中查找两次并输出它匹配的行。如果xz出现一次,我不想知道。

Running the following:

运行以下内容:

cat lines | grep "xz"

Tells me every line with xz on, but I only want to see lines with xz appearing twice.

告诉我 xz 打开的每一行,但我只想看到 xz 出现两次的行。

How can I make the pattern search repeat in the same line?

如何在同一行中重复模式搜索?

回答by Wiktor Stribi?ew

You can use

您可以使用

cat lines | grep 'xz.*xz'

Or just

要不就

grep 'xz.*xz' lines

The .*will match optional characters (any but a newline) between 2 xz.

.*将2之间匹配可选字符(但任何一个新行)xz

In case you need to use look-arounds, you will need -Pswitch to enable Perl-like regexps.

如果您需要使用环视,则需要-P切换以启用类似 Perl 的正则表达式。

回答by Kent

awk is one way to go:

awk 是一种方法:

awk -F'xz' 'NF==3' file

or

或者

awk 'gsub(/xz/,"")==2' file

another benefit awk brings you is, it is easier to check a pattern matched less then n times, exact n timesor greater than n times. you just change the ==into <, <=, >, >=

awk 为您带来的另一个好处是,可以更轻松地检查匹配的模式less then n times,exact n timesgreater than n times. 你只要把它==改成<, <=, >, >=

回答by karakfa

If you want to output the matching lines in full you don't need the options

如果要完整输出匹配的行,则不需要选项

grep 'xz.*xz' filename

will do

会做