Reputation: 95
I'm trying to put timestamp at the beginning of a file each time I call the awk command
I have a script with some commands and I want when I run a command to put that event to a log file with timestamp but I want that line to be at the begin of the log file each time.
with echo I can do it but the it goes at the end of file
echo "$(date +%d/%m/%Y) - $(date +%T)" ' - Script event 1' >> log.txt
I try with awk but I can't print date-time
awk -i inplace 'BEGINFILE{print "$(date +%d/%m/%Y) - $(date +%T) - Script event 1"}{print}' log.txt
So I want something like that
awk -i inplace 'BEGINFILE{print "$(date +%d/%m/%Y) - $(date +%T) - Script event 1"}{print}' log.txt
(......
some commands
......)
awk -i inplace 'BEGINFILE{print "$(date +%d/%m/%Y) - $(date +%T) - Script event 2"}{print}' log.txt
(......
some commands
......)
awk -i inplace 'BEGINFILE{print "$(date +%d/%m/%Y) - $(date +%T) - Script event 3"}{print}' log.txt
and my output log.txt to be
01/01/2021 - 16:50:05 - Script event 3
01/01/2021 - 16:52:15 - Script event 2
01/01/2021 - 16:54:25 - Script event 1
Upvotes: 1
Views: 906
Reputation: 1303
Using GNU awk for -i inplace
and time functions, use strftime()
to add timestamp at the starting of file.
awk -i inplace 'BEGINFILE{print strftime("%d/%m/%Y - %T") " - Script event 1"}{print}' log.txt
Upvotes: 4
Reputation: 246774
awk doesn't have the shell's command substitution syntax.
To capture the output of an external command, you use an awk pipe with getline
awk 'BEGIN {
cmd = "date \"+%F %T\""
cmd | getline timestamp
close(cmd)
print ">>", timestamp, "<<"
}'
>> 2021-07-17 09:36:06 <<
or, for reading multiple lines from an external command, a while loop:
awk 'BEGIN {
cmd = "seq 5"
while ((cmd | getline line) > 0) {
print ">>", line, "<<"
}
close(cmd)
}'
>> 1 <<
>> 2 <<
>> 3 <<
>> 4 <<
>> 5 <<
Of course, with GNU awk, use the builtin time functions
Upvotes: 0