【问题标题】:Can someone explain this AWK command?有人可以解释这个 AWK 命令吗?
【发布时间】:2020-10-01 16:43:20
【问题描述】:

我试图计算一个小时列表的平均值,我发现一个运行良好的 awk 命令,但我想知道它是如何工作的。

这是我的工作时间列表:

20:09
19:24
19:28

这就是程序

awk -F':' '
BEGIN {
    total=0;
}
{
    total+=(($1*3600)+($2*60)+$3);
} 
END {
    a=(total/NR); 
    printf "%02d:%02d:%02d\n",(a/3600),((a/60)%60),(a%60)
}' file

我了解第一部分以及它如何将所有内容转换为秒,仅此而已。

【问题讨论】:

    标签: unix awk


    【解决方案1】:

    您能否根据 OP 显示的尝试尝试以下解释。

    # Start awk program from here, set field separator as :
    awk -F':' '
    # The BEGIN block is only executed once, when the script starts
    BEGIN{
      # Initialize total
      total=0
    }
    # Main script executes for each input line
    {
      # Convert to seconds: Multiply first field $1 by 3600 and second by 60
      # then add the terms together, and add to total
      total+=(($1*3600)+($2*60)+$3)
    }
    # The END block executes when we have finished reading all lines
    END{
      # Calculate average: divide total by number of lines
      a=(total/NR)
      # Print result, where a/3600 is hours,
      # (a/60)%60 is remainder in minutes, a%60 remainder seconds
      # -- the %02d format specifier takes care to discard any decimals
      printf "%02d:%02d:%02d\n",(a/3600),((a/60)%60),(a%60)
    }
    ' file   # input file name
    

    【讨论】:

      【解决方案2】:

      简答:此代码计算位于文件file中的某些计时的平均持续时间

      我假设你有一个看起来像这样的文件:

      00:02:30: something1
      00:01:14: something2
      01:02:04: something3
      

      我还假设前三个值表示以小时、分钟和秒为单位的持续时间。

      代码所做的是每行提取持续时间并将其转换为总秒数并将其添加到值total。处理完所有行后,它会通过将其除以 NR 来计算平均持续时间,NR 表示已处理的总行数。然后它通过将平均值转换回hh:mm:ss来打印出平均值

      注意:代码可以简化成

      awk -F':' '{t+=3600*$1 + $2*60 + $3}
                 END{t/=NR; printf "%02d:%02d:%02d\n",t/3600,(t/60)%60),(t%60) }' file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        • 2016-12-09
        • 2013-01-09
        • 2012-04-19
        相关资源
        最近更新 更多