GREP between last occurrences of two strings

Hi I have the server.log file as:

Server Stopped
ABC
DEF
GHI
JKL
Server Started
MNO
PQR
STU
Server Stopped
VWX
YZ
ABC
Server Started
Server Stopped
123
456
789
Server Started



I want to get only this in the output to a log file :

Server Stopped
123
456
789
Server Started

i.e. The text between last Server stopped and Server Started and ignore others.
 

Can someone please help. I had look into tac but not getting the exact solution.

An awk approach:

awk '
        /Server Stopped/ {
                f = 1
                S = $0
                next
        }
        f && !/Server Started/ {
                S = S RS $0
                next
        }
        /Server Started/ {
                f = 0
                S = S RS $0
        }
        END {
                print S
        }
' file
1 Like

Hi,
Another solution with sed:

sed -n '/Server Stopped/h;/Server Stopped/,/Server Started/{/Server Stopped/b;H;};${x;p;}' file

Regards.

1 Like

Hi

Can you please explain the sed one...I am confused with the last part

/Server Stopped/h ==> if line we found 'Server Stopped', we initialize hold buffer with it.
/Server Stopped/,/Server Started/{/Server Stopped/b,H;} ==> Between lines 'Server Stopped' and 'Server Started', if the line is 'Server Stopped', we will at the end of the sed command to begin to the next line, else adds the other lines in the hold buffer.
${x,p;} ==> if last line, swap the hold buffer and the current buffer and the current buffer is displayed.

1 Like

Try also (untested):

tac server.log | awk '/server started/,/server stopped/; /server stopped/ {exit}' | tac

Just another awk version

awk '/Server Stopped/{f=""}/Server Stopped/,/Server Started/{f=f RS $0}END{print f}' infile

--ahamed

Hello,

One more approach for same.

awk -vs1="Server" 'BEGIN{ print s1 "Stopped" } /^[0-9]/ {print} END{print s2 "Started"}' starting_ending_text

Output will be as follows.

Server Stopped
123
456
789
Server Started

Thanks,
R. Singh

1 Like

Try something like :

$ tail -$(grep -m1 -n 'Server Stopped' <(tac file) | cut -d':' -f1) file
Server Stopped
123
456
789
Server Started
1 Like

python shell:

>>> import re
>>> text = '''
... Server Stopped
... ABC
... DEF
... GHI
... JKL
... Server Started
... MNO
... PQR
... STU
... Server Stopped
... VWX
... YZ
... ABC
... Server Started
... Server Stopped
... 123
... 456
... 789
... Server Started
... '''
>>> pattern = '(^Server Stopped\s*\n^(?:\d+\n)+^Server Started)'
>>> for found in re.search(pattern,text,re.M).groups():                                
...    print found
... 
Server Stopped
123
456
789
Server Started
1 Like