3/11/2023 0 Comments Copy log messages to another file![]() Well, those are just but a few examples on how to extract log lines of specific dates from a log file using sed and grep commands. For example, to print lines from April 7th to April 8th sed -n '/^Apr 7/,/^Apr 9/' test.logĪpr 8 10:32:01 amos ntpd: Soliciting pool server 192.168.71.138Īpr 8 10:32:10 amos ntpd: Soliciting pool server 192.168.34.2 If there are more than one line of the last date specified in the range, then you need to include the next date after the specified last date in the range and delete the last line. The above, as you can see prints all the lines from the specified first date up to including the only the first line of the specified last date. To extract log lines of a specific date, say 6th April, sed -n '/^Apr 6/p' test.logĪpr 6 07:00:13 amos ntpd: Soliciting pool server 192.168.206.2Īpr 6 07:00:19 amos ntpd: Soliciting pool server 192.168.206.2 You can check it by following the link below ĭelete Lines Matching a Specific Pattern in a File using SED In our previous guide, we discussed how to delete lines matching a specific pattern in a file using SED. Next, let us see how to use grep to extract log lines of specific dates on a log file. To get the lines of specific date range, say from April 6th to April 7th grep -E "Apr 6|Apr 7" test.logĪpr 6 09:12:14 amos ntpd: Soliciting pool server 192.168.206.2Īpr 6 09:12:15 amos ntpd: Soliciting pool server 192.168.206.2Īpr 7 07:22:52 amos ntpd: Soliciting pool server 192.168.71.138 Using sed to Extract Log Lines For example, to get the logs for specific date and time based on the date format on the log file, for example, 8th April, 09:22 grep "$(date -d '6 day ago' +'%b %d 09:22' | sed 's/0//')" test.log If you have different date formats, you would definitely play around with the date command to get the your right format. ![]() ![]() To extract events that happened four days ago from the current date grep "$(date -d '6 day ago' +'%b %d'| sed 's/0//')" test.logĪpr 8 09:22:52 amos ntpd: Soliciting pool server 192.168.34.2Īpr 8 09:22:54 amos ntpd: Soliciting pool server 192.168.71.138Īpr 8 09:22:56 amos ntpd: Soliciting pool server 192.168.34.2Īpr 8 09:22:58 amos ntpd: Soliciting pool server 192.168.71.138Īpr 8 09:23:00 amos ntpd: Soliciting pool server 192.168.34.2Īpr 8 09:23:52 amos ntpd: Soliciting pool server 192.168.71.138Īpr 8 09:22:54 amos ntpd: Soliciting pool server 192.168.34.Īs you can see above, the date command prints the date and removes the leading zero so that the format of the date matches the dates on the log file. To begin with, let us see examples on how to use grep to extract log lines of specific dates from a log file. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |