Extract Log Lines Between Two Timestamps with a Bash Script

You have a 400 MB log file from your Graylog node or your home server's OPNsense syslog, and you need the lines between 10:05 and 10:15 on March 15. You could open it in a text editor and scroll. You could write an awk one-liner that breaks when the log format shifts from space-separated to ISO-8601. Or you can use a small bash script that handles both formats, validates its inputs, and gives you a clear error message when something is wrong.

This is extract_range.sh. It takes a logfile path and two timestamps, then prints every line whose leading timestamp falls within that range, inclusive of both boundaries. No temp files. No external dependencies beyond GNU date and standard bash. I verified it in a clean Ubuntu container before publishing this post.

Verified terminal output of extract_range.sh — real test runs in a clean, network-isolated container.

Why not just use awk or sed?

You can. For a single-format log file, an awk range pattern works fine. The problem is that real logs are messy. My server logs from the Pi-Auto build use space-separated timestamps (2024-06-01 08:30:00), while application logs from the same machine emit ISO-8601 with a T separator (2024-06-01T08:30:00). A single awk pattern handles one or the other. This script normalizes both before comparing epoch seconds, so you don't have to remember which format a given log uses.

The strict mode and argument handling

The first three lines after the shebang do more work than they look like:

set -euo pipefail

This means: exit immediately if any command fails (-e), treat unset variables as errors (-u), and propagate the leftmost failure in a pipeline (pipefail). Without pipefail, a command like grep pattern file | wc -l would report success even if grep found nothing. In a script that's supposed to tell you when something is wrong, that silence is worse than an error.

The argument check is explicit. Three arguments required: logfile, start timestamp, end timestamp. If you get the count wrong, the script prints usage to stderr and exits with code 1. I keep exit codes distinct (1 for usage, 2 for file problems, 3 for timestamp problems) so that if you wrap this in a larger pipeline or cron job, you can branch on the failure reason without parsing error messages.

File checks before doing anything expensive

Before the script touches the log content, it confirms the file exists and is readable. This matters more than it sounds. If you're running this from a cron job or an Ansible task against a remote server, a missing log file (maybe logrotate just fired) should produce a clean exit 2, not a cryptic "No such file or directory" buried in a pipeline three stages deep.

Parsing the user-supplied timestamps

The script converts your start and end timestamps to epoch seconds using GNU date -d. This accepts a wide range of formats: "2024-03-15 10:05:00", "2024-03-15T10:05:00", "Mar 15 10:05:00", even relative expressions like "yesterday". If date can't parse the string, the script exits with code 3 and tells you which argument was bad.

It also checks that start is less than or equal to end. This sounds obvious, but I've written enough throwaway scripts where I accidentally swapped the arguments and got an empty result with no error. A two-second check that saves ten minutes of confusion.

The main loop: handling mixed timestamp formats

This is the part that makes the script longer than a one-liner. For each line in the file, the script extracts the first whitespace-delimited token as the candidate timestamp. Then it checks whether that token contains a T character.

If it does, the token is ISO-8601 (2024-06-01T08:30:00). The script replaces the T with a space to get a format GNU date handles cleanly.

If it doesn't contain a T, the timestamp is split across two tokens (2024-06-01 08:30:00). The script grabs the first token, then pulls the second token from the remainder of the line, and joins them with a space.

Either way, the result gets fed to date -d for conversion to epoch seconds. If the conversion fails (the "timestamp" isn't actually a timestamp, maybe it's a log line that starts with something else), the script skips that line with continue rather than aborting. This is intentional: a single malformed line in a 400 MB file shouldn't kill your extraction.

The comparison is straightforward integer arithmetic on epoch seconds. Both boundaries are inclusive, so a line at exactly 10:05:00 and a line at exactly 10:15:00 both appear in the output.

Why compare epoch seconds instead of the strings

You could try to compare the timestamp strings directly, but that falls apart the moment two lines use different formats. A T-separated stamp and a space-separated stamp do not order against each other as plain text, and the whole reason this script exists is that a single log mixes both. Converting every candidate to an integer epoch second gives you one total order to test against, no matter how the line was written. The two boundary checks then become ordinary integer comparisons: greater than or equal to the start, less than or equal to the end. That is what makes both ends inclusive without any special-casing of the first or last line.

The final line with no trailing newline

The read loop is written as read -r line || [ -n "$line" ], and that second half is doing real work. A log file that is still being appended to, or one that was cut off mid-write, frequently has no newline on its last line. A plain while read stops after the final complete line and silently discards whatever partial line is left behind. The || [ -n "$line" ] clause keeps the loop body running one more time for the remainder in the buffer, so a boundary line that happens to sit on that last unterminated line is still captured instead of quietly dropped.

Verification

I ran five test cases in a clean Ubuntu container. All five passed, zero failures. Here's what they covered:

A normal range extraction against app.log with space-separated timestamps returned three lines:

2024-03-15 10:05:00 WARN high memory usage 2024-03-15 10:10:00 ERROR disk full on /var 2024-03-15 10:15:00 INFO recovery complete

Both boundary lines are present, confirming the inclusive check.

An empty file (empty.log) produced no output and exited cleanly. No error, no crash, just silence, which is correct.

A mixed-separator test against a file at /tmp/testdata/my logs/server t.log (note the spaces in the path) handled both T-separated and space-separated timestamps in the same file:

2024-06-01T08:30:00 mid event 2024-06-01 09:00:00 space separated line 2024-06-01 09:30:00 end boundary hit

The spaces in the filename work because the script quotes "$f" everywhere it uses the path.

Calling the script with no arguments exited with code 1, as expected. Passing "not-a-real-date" as the start timestamp exited with code 3.

The script

#!/usr/bin/env bash
set -euo pipefail

[ $# -eq 3 ] || { echo "Usage: $0 <logfile> <start_ts> <end_ts>" >&2; exit 1; }

f="$1" s="$2" e="$3"

[ -f "$f" ] || { echo "Error: no such file: $f" >&2; exit 2; }
[ -r "$f" ] || { echo "Error: unreadable: $f" >&2; exit 2; }

se=$(date -d "$s" +%s) || { echo "Error: bad start timestamp: $s" >&2; exit 3; }
ee=$(date -d "$e" +%s) || { echo "Error: bad end timestamp: $e" >&2; exit 3; }
[ "$se" -le "$ee" ] || { echo "Error: start must be <= end" >&2; exit 3; }

while IFS= read -r line || [ -n "$line" ]; do
  ts="${line%% *}"
  if [[ "$ts" == *T* ]]; then
    tok="${ts//T/ }"
  else
    rest="${line#* }"
    tok="$ts ${rest%% *}"
  fi
  ep=$(date -d "$tok" +%s 2>/dev/null) || continue
  if [ "$ep" -ge "$se" ] && [ "$ep" -le "$ee" ]; then
    printf '%s\n' "$line"
  fi
done < "$f"

How to use it

Make it executable and run it with three arguments:

bash extract_range.sh /var/log/graylog/server.log '2024-03-15 10:05:00' '2024-03-15 10:15:00'

If your timestamps use the ISO format with a T, that works too:

bash extract_range.sh '/tmp/testdata/my logs/server t.log' '2024-06-01T08:30:00' '2024-06-01 09:30:00'

Pipe the output to less for interactive reading, or redirect to a file if you want to keep the extracted window:

bash extract_range.sh /var/log/syslog '2024-01-01 00:00:00' '2024-12-31 23:59:59' > /tmp/full-year.log

One caveat: this script reads the file line by line in a bash while loop. For files under about a gigabyte, that's fine. If you're extracting from a 50 GB log, pre-filter with grep or zgrep before handing it to this script. Bash's read loop is not going to outperform C.


Luke Keam
Spot a bug or want a custom utility built? I'd love to hear from you. Get in touch
Luke Keam | techgeek.biz