Parse Log Files with sed

less than 1 minute read

Published:

When parsing log files sed is not the go-to tool for most techs, but it offers a pretty neat feature: the ability to easily search a log file for a specific date/time range.

Pattern Matching

sed -n '/Dec 30 13:00/p' /var/log/messages

Date Range Matching

sed -n '/Dec 30 13:00/,/Dec 30 14:00/p' /var/log/messages

Change Delimiters

If your search term contains the character /, you can change the delimiter used by sed:

sed -n '\|30/Dec/2015:21|,\|30/Dec/2015:23|p' /var/log/httpd/access.log

Command Break Down

-n This flag tells sed to suppress all output except for matching lines.

/Dec 30 13:00/ Match lines containing the string “Dec 30 13:00”. The search term can be a regular expression, /regexp/.

/Dec 30 13:00/,/Dec 30 14:00/ Match all content from the first “Dec 30 13:00” to the first “Dec 30 14:00”.

p Print the current pattern space.

\| Change the delimiter to |. The | can be any character.