Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Lines after specific occurrence in linux log file

Tags:

linux

grep

bash

I am trying to get information of USB attached in linux from syslog file(/var/log/messages) .

for that I read log file and get the information. Now what i do is that I read syslog file and try to find Last occurrence (newly attached usb) of "New USB device found". then I'm trying to read next 16 lines after that to get USB info (size, serial, manufacturer etc).

At the moment I'm using following syntax:

grep -A 20 -e 'New USB device found' /var/log/messages | tail -n 16 > usb_detail

But this syntax fails in one case. if there are 25 lines after " New USB..." then I'll get last 16 and then i'll skip actual information that is required. if there are only 16 lines after "New USB ..." then it will work fine and I'll get required information.

So what I want is to get immediate 16 lines after last occurrence of "New USB device found". Not the last 16 lines after "New USB device found".

Please let me know if my question isn't clear. Thanks in advance for your time.

like image 924
user115079 Avatar asked Feb 22 '26 03:02

user115079


1 Answers

What's wrong with

fgrep -A 16 'New USB device found' /var/log/messages | tail -n 16

16 lines is consistently enough for what I see in my logs (the longest I have is 10). If grep has fewer than 16 lines, it will truncate there, and you'll get a couple useless lines before the new device, but grep prints -- between blocks of matches when using context.

like image 60
David Souther Avatar answered Feb 25 '26 05:02

David Souther



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!