Print the lines between two dates from the log usi

2020-07-25 09:50发布

I have a log and I want to print all the lines from the log between two dates 02/04/2015:14:23:00 and 02/04/2015:14:23:59

标签: linux bash
2条回答
女痞
2楼-- · 2020-07-25 10:29

Another approach with a sed one-liner: sed -n '/start/,/end/p' log.txt

$ cat /tmp/log.txt
before
before
before
a log line containing 02/04/2015:14:23:00 and some other stuff
between
between
a log line containing 02/04/2015:14:23:59 and some other stuff
after
after

$ sed -n '/02\/04\/2015:14:23:00/,/02\/04\/2015:14:23:59/p' /tmp/log.txt
a log line containing 02/04/2015:14:23:00 and some other stuff
between
between
a log line containing 02/04/2015:14:23:59 and some other stuff

Please note it will not work as expected if start and end tokens are in the same line.

查看更多
虎瘦雄心在
3楼-- · 2020-07-25 10:51

This case is very simple - use grep and match 02/04/2015:14:23::

grep '02/04/2015:14:23:' log.txt

General/universal case is more complicated. You have to find first and last line, and then print lines.

To find first and last line, use something like this (dates only for example):

FIRST=`grep -n '02/04/2015:14:30:12' log.txt | head -n 1 | cut -f 1 -d:`
LAST=`grep -n '02/04/2015:14:43:43' log.txt | tail -n 1 | cut -f 1 -d:`

Command greps all lines matching some pattern, than selects first/last matching line, and cuts the line number from it.

This can be used with tail and head to select matching lines:

tail -n +$FIRST log.txt | head -n $(($LAST-$FIRST+1))

Following script summarize the operations:

#!/bin/bash

START_PATTERN=$1
END_PATTERN=$2
FILE=$3

FIRST=`grep -n "$START_PATTERN" $FILE | head -n 1 | cut -f 1 -d:`
LAST=`grep -n "$END_PATTERN" $FILE | tail -n 1 | cut -f 1 -d:`

tail -n +$FIRST $FILE | head -n $(($LAST-$FIRST+1))
查看更多
登录 后发表回答