4

I have three columns like this:

18:37:12 18:37:31 0  
18:37:01 18:37:18 0

I would like to have the third column be populated with the difference in seconds of the two first columns like this:

18:37:12 18:37:31 19  
18:37:01 18:37:18 17

I am using this:

nova migration-list | grep completed | awk '{ print substr($22,12,8), substr($24,12,8) }' | awk 'BEGIN{ FS=" " } { print $0, $2-$1 }'

I appreciate any help

2 Answers 2

4

On a GNU system:

awk '{"date -d "$1" +%s"|getline one; "date -d "$2" +%s"|getline two; \
         print $1, $2, two-one}' file.txt
  • "date -d "$1" +%s"|getline one gets the seconds since epoch (using GNU date) for field 1, save in variable one

  • "date -d "$2" +%s"|getline two does the same for field 2, and save the result as variable two

  • print $1, $2, two-one prints the field one, two, and subtraction of variable two and one

Example:

% cat file.txt
18:37:12 18:37:31 0
18:37:01 18:37:18 0

% awk '{"date -d "$1" +%s"|getline one; "date -d "$2" +%s"|getline two; print $1, $2, two-one}' file.txt
18:37:12 18:37:31 19
18:37:01 18:37:18 17
1
  • That's what i was looking for. Thank you! Oct 21, 2016 at 23:56
4

Using GNU awk's builtin time functions:

awk '
  function to_time(time,   t,a) {
    split(time, a, ":")
    t = mktime("1970 1 1 " a[1] " " a[2] " " a[3])
    return t
  }
  {print $1, $2, to_time($2) - to_time($1)}
' file
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .