在单独的行或单行上的模式之间进行 Grep

sup*_*rme 3 grep wildcards

所以我需要的是 grep 仅匹配我的匹配模式之间(并包括)之间的文本。

像这样的东西(不要介意文字,这只是一些乱码:D):

asdgfasd gasd gdas g This will be this one day ksjadnbalsdkbgas asd gasdg 
asdgasdgasdg dasg dasg dasg This will be this next day adf gdsf gdsf sdfh dsfhdfsh
asdf asdf asd fesf dsfasd f This will won' not this day asdgadsgaseg as dvf as d vfa se v asd
dasfasdfdas fase fasdfasefase fasdf This not what shoes day asdjbna;sdgbva;sdkbcvd;lasb ;lkbasi hasdli glais g
Run Code Online (Sandbox Code Playgroud)

所以我想要的是这样的: cat theabovetext|grep -E "^This * day$" 输出:

This will be this one day
This will be this next day
This will won' not this day
This not what shoes day
Run Code Online (Sandbox Code Playgroud)

所以基本上我只想获取“This”和“Day”之间的文本(包括“This”和“day”),无论中间有多少个字符,也不管“This”之前和“Day”之后有多少个字符。即使输入全部在一行上,这也需要工作,所以:

asdgfasd gasd gdas g This will be this one day ksjadnbalsdkbgas asd gasdg asdgasdgasdg dasg dasg dasg This will be this next day adf gdsf gdsf sdfh dsfhdfsh asdf asdf asd fesf dsfasd f This will won' not this day asdgadsgaseg as dvf as d vfa se v asd dasfasdfdas fase fasdfasefase fasdf This not what shoes day asdjbna;sdgbva;sdkbcvd;lasb ;lkbasi hasdli glais g

必须输出这个:

This will be this one day This will be this next day This will won' not this day This not what shoes day

注意这里的输出仍然在一行上。

Eri*_*ouf 5

使用 GNU,grep您可以执行以下操作:

grep -o 'This.*day' theabovetext
Run Code Online (Sandbox Code Playgroud)

(请注意,您不需要,cat因为grep知道如何读取文件)

-o标志表示仅显示与模式匹配的行部分。

我怀疑其他版本grep也支持这个标志,但它不在 POSIX 中,所以它不一定是可移植的。

  • 您可以使用 PCRE 模式,以便可以将量词设置为非贪婪 `grep -oP 'This.*?day' theabovetext`,但这会将每个匹配项放在单独的行上,在这两种情况下 (3认同)