Question

I am writing a script in bash using awk (mawk) and I would like to return the output of a system command to awk.

I have a variable called created that is in ISO format: 2013-12-26T17:03:05Z and I want to convert it from ISO to epoch. I can run this line created_epoch=system("date +\%s -d " created) and it prints the output to the terminal, but the variable created_epoch is equal to 0, not the epoch time.

Does anyone know how I can convert an ISO format to epoch in awk?

Thanks!

Was it helpful?

Solution

Try using getline into a variable from a pipe instead of system

cmd="date +\%s -d "created; cmd | getline current_time

https://www.gnu.org/software/gawk/manual/html_node/Getline_002fVariable_002fPipe.html#Getline_002fVariable_002fPipe

The system command returns the exit status returned by the command that was executed as its value. http://www.delorie.com/gnu/docs/gawk/gawk_137.html

OTHER TIPS

The system command in awk, as in C, returns the exit status of a command, and not the output of said command. As others have suggested, your best bet is using getline from a pipe

I ran into a similar problem a while back and rolled my own exec function, here it is:

# get the output of a command
function exec(cmd,      data) {
  while ((cmd | getline data) > 0) printf("%s", data);
  close(cmd);
}

Then using the function defined above, you should do something like this:

epoch = exec("date +%s -d \"<ISO DATE>\"")

where <ISO DATE> is an ISO conformant date/timestamp.

Example:

# helper.awk is where `exec` is defined
awk '@include "helper.awk"; BEGIN
{ 
  epoch = exec("gdate -d \"2014-02-14T12:30\" +%s");
  print epoch
}'
# 1392406200

Do it like this:

created_epoch=$(date +\%s -d "$created")
echo $created_epoch
1388077385
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top