Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Created Nov 12, 2021
Embed
What would you like to do?
#!/usr/bin/env ksh
typeset -T Record=(
integer uid
integer date=0
typeset description
)
typeset -T Log=(
Record -h '(internal) Array of log records.' -a records
typeset -h 'Path to the log file' fileName
typeset -h 'The date format to use for printing' fmt=%m/%d/%C%y
function readLog {
if [[ ! ( -f ${_.fileName} && -r ${_.fileName} ) ]]; then
printf 'Log file: %q not found.\n' "${_.fileName}" >&2
return 1
fi
typeset uid date desc
integer n
while IFS=, read -r uid date desc; do
_.records[n++]=(uid=uid; date=$(printf '%(%s)T' "$date"); description=$desc)
done <"${_.fileName}"
}
function printLastNDays {
if [[ $1 != +([[:digit:]]) ]]; then
printf '%s: Must specify a positive integer of days\n' "${.sh.fun}" >&2
return 1
fi
integer fromTime idx
printf -v fromTime '%(%s)T' "$1 days ago"
for idx in "${!_.records[@]}"; do
((_.records[idx].date > fromTime)) || continue
#printf "UID: %d\nDate: %(${_.fmt})T\nDescription: %s\n\n" \
# "${_.records[idx].uid}" "${_.records[idx].date}" "${_.records[idx].description}"
printf 'UID: %d\nDate: %s\nDescription: %s\n\n' \
"${_.records[idx].uid}" "$(/bin/date -d "@${_.records[idx].date}" "+${_.fmt}")" "${_.records[idx].description}"
done
}
)
function main {
Log myLog=(fileName=/dev/fd/3)
myLog.readLog &&
myLog.printLastNDays 7
}
#typeset -ft main .sh.type.Log.readLog .sh.type.Log.printLastNDays
main "$@" 3<<-'EOF'
123,07/16/2015,foo
124,07/17/2015,bar
125,07/18/2015,baz
126,07/19/2015,bork
EOF
# vim: set fenc=utf-8 ff=unix ft=sh noet :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment