首页 > 解决方案 > 如何遍历文件并在bash中应用日期?

问题描述

我确定这已得到解答,但我的谷歌搜索有问题。

文件是这样的:

2020-01-01 10:33
2020-01-01 14:04
2020-01-01 17:22
2020-01-20 14:04
2020-01-21 03:33
2020-01-22 14:06 

如何遍历每一行并应用date +"%b%d"使文件看起来像:

Jan1 10:33
Jan1 14:04
Jan1 17:22
Jan20 14:04
Jan21 03:33
Jan22 14:06

标签: bashshell

解决方案


你基本上有两个选择。

  1. 使用shell,遍历文件中的每一行,将每一行读入一个变量并使用格式输出日期+'%b%d %H:%M';或者
  2. 使用 GNU awk,从每一行创建一个datespec,并传递mktime给创建一个时间戳,然后可以使用它strftime来输出 format "%b%d %H:%M"

重击解决方案

while read -r line; do 
    date -d "$line" +'%b%d %H:%M'
done < file

GNU awk 解决方案

awk '{
    gsub(/[-:]/," ",$0)                # remove '-' and ':'
    ts=mktime($0 " 00")                # add " 00" creating datespec, create timestamp
    print strftime("%b%d %H:%M",ts)    # output new date format
}' file

注: mawk,至少从版本 1.3.3 开始还支持mktimestrftime

示例输出

在这两种情况下,输出都是相同的:

Jan01 10:33
Jan01 14:04
Jan01 17:22
Jan20 14:04
Jan21 03:33
Jan22 14:06

如果您有其他问题,请查看并告诉我。


推荐阅读