Can anyone help me with this shell script to extract the logs within the specified timestamp. I don’t know what’s wrong with it. this is the script. when i tried to execute it, it says something like there is a error while parsing the date
#!/bin/bash
# Function to convert timestamp to seconds since epoch
convert_to_seconds() {
local timestamp=$1
date -d "$timestamp" +%s
}
# Check if correct number of arguments are passed
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <log_file_name> <start_timestamp> <end_timestamp>"
echo "Timestamps should be in the format '[HH:MM:SS:SSS][DD-MM-YYYY]'"
exit 1
fi
log_file=$1
start_timestamp=$2
end_timestamp=$3
# Convert start and end timestamps to seconds since epoch
start_seconds=$(convert_to_seconds "$start_timestamp")
end_seconds=$(convert_to_seconds "$end_timestamp")
# Check if log file exists
if [ ! -f "$log_file" ]; then
echo "File not found: $log_file"
exit 1
fi
# Read the log file line by line
while IFS= read -r line; do
# Extract the timestamp from the log line
if [[ $line =~ ([[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{3})][([0-9]{2}-[0-9]{2}-[0-9]{4})] ]]; then
log_time="[${BASH_REMATCH[1]}][${BASH_REMATCH[2]}]"
log_seconds=$(convert_to_seconds "$log_time")
# Check if log time is within the specified range
if [ "$log_seconds" -ge "$start_seconds" ] && [ "$log_seconds" -le "$end_seconds" ]; then
echo "$line"
fi
fi
done < "$log_file"
New contributor
Arav Stark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.