Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed in Linux to extract lines from a log file

I have a log file which prints the following lines:

01:15:21.882 DEBUG [SampleProcess] 
Sample Message
01:15:21.882 DEBUG [SampleProcess1] 
Summary Report
Sample Text1: 126
Sample Text2: 2330
Sample Text3: 2331
Sample Text4: 0
01:15:21.883 DEBUG [SampleProcess2] 

I was able to extract the Summary Report by using the below sed command

 sed -n '/Summary Report/,/Sample Text4/p' samplefile.log 

However, I also want to print the timestamp when the Sample Report was generated.

So, currently with

sed -n '/Summary Report/,/Sample Text4/p' samplefile.log

I see the output as

Summary Report
    Sample Text1: 126
    Sample Text2: 2330
    Sample Text3: 2331
    Sample Text4: 0

I want the output as

01:15:21.882 DEBUG [SampleProcess1] 
    Summary Report
    Sample Text1: 126
    Sample Text2: 2330
    Sample Text3: 2331
    Sample Text4: 0
like image 1000
user2967948 Avatar asked Dec 31 '25 21:12

user2967948


1 Answers

This might work for you (GNU sed):

sed -n '/^..:..:..\./{N;/Summary Report/!D;:a;N;/Sample Text4/!ba;s/\n/&    /gp}' file

Switch off automatic printing. If the current line is a timestamp and the next is not a Summary Report, delete the first line and repeat. Otherwise, gather up the following lines until the Sample Text4, indent all but the first line, print and repeat.

like image 199
potong Avatar answered Jan 03 '26 12:01

potong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!