Read lines after a specific word.
I have a text file (basically a log file) in which i have couple of occurrence of word "address 5". Now my requirement is that I reach to last occurrence of this word and then output this line and next 20 lines in some temp file for further manipulation.
or from reverse side: go to end of file and get the first occurrence and output that line and next 20 lines in some temp file. I'm using Cent OS bash.. thanks in advance. and do let me know if my question isn't clear. |
How about
Code:
grep -A 20 -e 'address 5' input > output If you only want the last match, try Code:
grep -A 20 -e 'address 5' input | tail -n 21 > output |
Quote:
OP asked for the last match and the following 20 lines. I tested this and it returned only the following 20 lines. Daniel B. Martin |
Quote:
|
Quote:
gnu grep now has two options for controlling this. You can change the separator or leave it out entirely. Code:
grep --no-group-separator -A 20 -e 'address 5' input > output No, they're not mentioned in the man page yet, but they are in the info page. |
Opening this thread again
|
I'm sorry to tell you but I've got a bug in following command:
Quote:
so it means if there are 20 lines after last occurrence of "New USB device found" then I'll get ending 16 lines. and this is not what I'm looking for. I want next 16 lines after "New USB device found". Hope this time I'm making it more clear. |
'grep -A 16 ...' & 'tail -n 17'
:) |
@descendant_command: Just what do you think the command you posted is supposed to do?
@Kashif_Bash: Think about how the commands you are using work. "grep -A20" prints out every occurrence of the matched line, plus the 20 lines following them. Then that output is sent into "tail -n16", which filters out all but the last 16 lines. What you really want is the first 16 lines of the last 21 lines of the output. So what we need to do is run it through a second filter, head in this case. Code:
grep -A 20 -e 'New USB device found' /var/log/messages | tail -n 21 | head -n 16 > usb_detail Code:
tac /var/log/messages | grep -B16 -m1 'New USB device found' | tac > usb_detail It may be possible to come up with something cleaner using sed or awk. I'll have to think about it a bit. Edit: Here's a quickly-knocked-out awk expression that appears to do it, although it's a bit cumbersome. Likely grail or someone will come along and embarrass me with a much simpler version. ;) Code:
awk '/New USB device found/ { t=""; f=1 } ; { if ( f != 0 && f <= 17 ) { t=t"\n"$0 ; f++ } else{ f=0 }} END{ sub(/^\n/,"",t) ; print t }' /var/log/messages > usb_detail |
@david
It's not a command - it is a hint as to how to adjust the previous command so that it will work as desired. |
Ah, I see it now. You really should take time to explain such things more clearly. I had taken the "&" to be part of the suggested change, which of course is not right at all.
|
All times are GMT -5. The time now is 09:36 PM. |