Convert Unix timestamp to human-readable time
If the line starts with the unix timestamp, then this should do it:
perl -pe 's/^(\d+)/localtime $1/e' inputfilename
perl -p
invokes a loop over the expression passed with -e
which is executed for each line of the input, and prints the buffer at the end of the loop.
The expression uses the substition command s///
to match and capture a sequence of digits at the beginning of each line, and replace it with the local time representation of those digits interpreted as a unix timestamp. /e
indicates that the replacement pattern is to be evaluated as an expression.
If your AWK is Gawk, you can use strftime
:
gawk '{ print strftime("%c", $1) }'
will convert the timestamp in the first column to the current locale’s default date/time representation.
You can use this to transform the content before viewing it:
gawk '{ print gensub($1, strftime("%c", $1), 1) }' inputfile
As Dan mentions in his answer, the Gnu date(1)
command can be
given a -d
parameter with a date or timestamp that it will treat as
the date to be output. (This is not available in the POSIX or BSD
date(1)
commands, however.) @1571806800
is the format used to
specify a time_t
integer.
Here's a Bash shell function that acts as a filter, reading lines from the input, assuming any word starting a line that's all digits is a timestamp, and converting that to human-readable output in one of my favourite formats.
ts2hr() {
while read n rest; do
if [[ $n =~ ^[0-9][0-9]*$ ]]; then
echo "$(date -d @"$n" +"%Y-%m-%d %T")" "$rest"
else
echo "$n" "$rest"
fi
done
}
Here's what some input and output look like:
ts2hr <<____
1571806123 first line
# A comment?
1571720456 second date's here
Just a regular sentence.
1571547789 The last line.
____
2019-10-23 13:48:43 first line
# A comment?
2019-10-22 14:00:56 second date's here
Just a regular sentence.
2019-10-20 14:03:09 The last line.
You can tweak the function as necessary to handle the particular input
and output formats you require, as well as the tools you have
available. The above function is Bash mainly because the =~
operator
made the pattern match easier; if you need this in Bourne shell you'll
have to code the check differently, if indeed you need it at all.