【问题标题】:How can count the number of rows meeting a time condition in bash?如何计算bash中满足时间条件的行数?
【发布时间】:2018-01-11 18:24:14
【问题描述】:

我有一个包含 1000 行不同纪元时间的 txt 文件(1396848990 = Sun Apr 6 22:36:30 PDT 2014)。如何计算晚上 8 点到午夜之间发生的行数。

【问题讨论】:

标签: bash unix command-line terminal


【解决方案1】:

您可以使用awk 执行以下操作:

awk 'int(strftime("%H", $1)) >= 20 {print $1}' $input_file | wc -l

它将使用 strftime() 将 unix 纪元时间戳转换为小时 (%H),将其转换为整数 (int()) 并与数字 20 进行比较。如果数字更大 - 打印时间戳.

在外面,wc 可以负责计算打印的行数。

当然,您也可以使用awk

awk 'int(strftime("%H", $1)) >= 20 {n+=1} END{print n}' $input_file

它将默默地用零初始化变量n,并在最后打印结果。

编辑:strftime() 似乎是exist in GNU awk

$ awk -V
GNU Awk 4.1.3, API: 1.1 (GNU MPFR 3.1.4, GNU MP 6.1.0)

【讨论】:

  • 我认为 unix 中不存在 strftime... 我收到错误:awk: calling undefined function strftime input record number 1, file times.txt source line number 1 0
  • 也许你需要在你的机器上调用gawk ?你在 MacOS 上运行吗?默认情况下它可能没有 GNU awk。
【解决方案2】:

虽然awk 肯定更快、更容易阅读,但我认为您只能使用(现代)bash 来做到这一点。

这样的事情应该可以工作:

let counter=0; (while read -ra epoch; \ 
do [ $(printf "%(%H)T" ${epoch[0]}) -ge 20 ] && \ 
let "counter++"; done; echo $counter) <inputfile

它的工作方式类似于 Pavels 的回答,但使用 bash 的 printf 来格式化日期(可能仍然是 strftime 在幕后)。
reading 到数组 (-a) 和 let counter++ 仅适用于现代 bash (4?)

【讨论】:

    【解决方案3】:

    如果你的date 命令支持 -d (--date) 选项,怎么样:

    from=$(date +%s -d "Apr 6 20:00:00 PDT 2014")
    to=$(date +%s -d "Apr 7 0:00:00 PDT 2014")
    awk -v from=$from -v to=$to '$0 >= from && $0 <= to' file | wc -l
    

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 2013-10-14
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多