Convert epoch timestamp to file in place
I have a tab file with a timestamp in the third field that I need to change in epoch in bash.
Input example:
xyz@gmail.com SALE 2017-04-26 12:47:27 30.0 1 201704
xyz@gmail.com SALE 2017-04-26 12:46:15 20.0 2 201704
xyz@gmail.com PAYBACK 2017-04-18 08:02:31 95.0 3 201704
xyz@gmail.com SEND 2017-04-18 08:00:37 4800.0 4 201704
xyz@gmail.com SEND 2017-04-17 14:59:34 4900.0 5 201704
I tried awk 'BEGIN {IFS="\t"} {$3=system("date -d \""$3"\" '+%s'");print}' file
which gives the closest results, but it displays the epoch on one line and then shows the entry again on a new line with the timestamp as zero. I require everything in one record with the third field replaced.
source to share
With GNU awk:
$ cat tst.awk
BEGIN { FS=OFS="\t" }
{
$3 = mktime(gensub(/[-:]/," ","g",$3))
print
}
$ awk -f tst.awk file
xyz@gmail.com SALE 1493228847 30.0 1 201704
xyz@gmail.com SALE 1493228775 20.0 2 201704
xyz@gmail.com PAYBACK 1492520551 95.0 3 201704
xyz@gmail.com SEND 1492520437 4800.0 4 201704
xyz@gmail.com SEND 1492459174 4900.0 5 201704
With other awks:
$ cat tst.awk
BEGIN { FS=OFS="\t" }
{
cmd = "date -d \"" $3 "\" \047+%s\047"
if ( (cmd | getline line) > 0 ) {
$3 = line
}
close(cmd)
print
}
$ awk -f tst.awk file
xyz@gmail.com SALE 1493228847 30.0 1 201704
xyz@gmail.com SALE 1493228775 20.0 2 201704
xyz@gmail.com PAYBACK 1492520551 95.0 3 201704
xyz@gmail.com SEND 1492520437 4800.0 4 201704
xyz@gmail.com SEND 1492459174 4900.0 5 201704
wrt your script - there is no built-in awk variable named IFS
, system
returns the completion status of the last command run, not stdout, and you cannot include '
in any '
- script called from the shell.
wrt wants to do it "in place", no UNIX editor REALLY does the editing in place, and in GNU awk you can use -i inplace
to avoid specifying the tmp filename yourself. However, with any UNIX command, you can just do cmd file > tmp && mv tmp file
.
Note that this is one of the few suitable uses for getline
- see http://awk.freeshell.org/AllAboutGetline for other valid purposes and, most importantly, caveats and reasons not to use it if absolutely necessary.
source to share