Grep between patterns on separate lines or single line

grepwildcards

So what I would need is for grep to match only the text in between (and including) my match pattern.

So something like this (don't mind the text, it's just some garble :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

So what I want is something like this:
cat theabovetext|grep -E "^This * day$"
To output this:

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

So basically I want to ONLY get the text in between This and Day (including This and day) regardless of how many characters there are in between, and regardless of how many characters there are before This and after Day.
Also this needs to work even if the input is all on a single line, so this:

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

Has to output this:

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

N.B. the output here is still on a single line.

Best Answer

If you want lines to be processed separately (your first example) but for multiple matches per line to be output on a single line (as in your second example), then I don't think that's possible with grep alone.

However using the same This.*?day non-greedy match in perl itself you can do

$ perl -lne 'print join " ", /This.*?day/g' theabovetext1
This will be this one day
This will be this next day
This will won' not this day
This not what shoes day

while for the single-line input

$ perl -lne 'print join " ", /This.*?day/g' theabovetext2
This will be this one day This will be this next day This will won' not this day This not what shoes day
Related Question