【问题标题】:Insert missing dates in text file in Shell在 Shell 的文本文件中插入缺失的日期
【发布时间】:2022-01-11 20:01:13
【问题描述】:

我有一个包含以下元素的文本文件,其中第一列是日期,第二列是价格:

2014-03-16 35

2014-03-17 78

2014-03-18 90

2014-03-20 22

2014-03-21 90

2014-03-22 38

2014-03-24 92

我想填写缺少日期的文件并添加 NA 的价格,例如:

2014-03-16 35

2014-03-17 78

2014-03-18 90

2014-03-19 不适用

2014-03-20 22

2014-03-21 90

2014-03-22 38

2014-03-23 不适用

2014-03-24 92

非常感谢您的帮助

【问题讨论】:

    标签: linux shell date


    【解决方案1】:

    您可以使用这些代码来做到这一点:

    temp.txt 文件包含所有没有空行的数据。

    #get the started timestamp
    START=$(date -d `head -n1 temp.txt |awk '{print $1}'` +%s)
    #get the ended timestamp
    END=$(date -d `tail -n1 temp.txt |awk '{print $1}'` +%s)
    #output what you want
    cat temp.txt |awk -v start=$START -v end=$END '{total[$1]=$2}END{for (i =start; i<=end;i+=86400) {_t = strftime("%Y-%m-%d", i);if (_t in total){print _t,total[_t]}else{print _t" NA"}}}'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多