I have a log file which contains the following content:
Date: 2014-09-07
Price: 1.35
Amount: 20
ProcessedBy: Bill
Some other contents
Date: 2014-09-08
Price: 10.1
Amount: 15
ProcessedBy: Alice
Some other contents
Date: 2014-09-09
Price: 100
Amount: 2.6
ProcessedBy: Boss
Some other contents
I would like to use awk to find the last "Date", and print the following three lines.
Date: 2014-09-09
Price: 100
Amount: 2.6
ProcessedBy: Boss
I use the code:
awk '/Date/ {x=NR}; END{NR>=x && NR<=x+3} LOG_FILE
However, it seems that I cannot put NR output after END.
How can I get the following N lines after the last match?
Thank you for your attention!
$ awk '/^Date:/ {c=1; a=$0;next} c<=3{c=c+1;a=a"\n"$0}END{print a}' LOG_FILE
Date: 2014-09-09
Price: 100
Amount: 2.6
ProcessedBy: Boss
Taking the code one piece at a time:
/^Date:/ {c=1; a=$0;next}
Every time that a line starting with Date:
is encountered, assign counter c
to one, assign the line to the variable a
, and skip to the next line
c<=3{c=c+1;a=a"\n"$0}
If the counter is less than or equal to three, increment the counter and save the new line to the end of variable a
.
END{print a}
Print the last-seen value of a
.
$ awk -v RS= '/^Date:/ {a=$0} END{print a}' LOG_FILE
Date: 2014-09-09
Price: 100
Amount: 2.6
ProcessedBy: Boss
Taking the code one piece at a time:
-v RS=
awk
divides its input up into "records." This works by setting the record separator RS
to a blank line. (For GNU awk
, an empty RS
matches an empty line. For other versions of awk
, you may need to do something different.)
/^Date:/ {a=$0}
Every time a record is encountered that starts with Date:
, it is saved in the variable a
.
END{print a}
At the end of the run, the last-seen value of a
is printed.
$ awk -v RS= 'END{print $0}' LOG_FILE
Date: 2014-09-09
Price: 100
Amount: 2.6
ProcessedBy: Boss
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments