bash - 如何遍历文件并在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
解决方案
你基本上有两个选择。
- 使用shell,遍历文件中的每一行,将每一行读入一个变量并使用格式输出日期
+'%b%d %H:%M'
;或者 - 使用 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 开始还支持mktime
和strftime
)
示例输出
在这两种情况下,输出都是相同的:
Jan01 10:33
Jan01 14:04
Jan01 17:22
Jan20 14:04
Jan21 03:33
Jan22 14:06
如果您有其他问题,请查看并告诉我。
推荐阅读
- asp.net - 为什么asp vb从ajax调用函数后面的代码返回404未找到
- javascript - 自动化将在文本框中键入的键盘事件
- design-patterns - 此示例中使用了哪些设计模式?
- python - 将 2 列类似计数器的 csv 文件转换为 Python 集合。计数器?
- c# - NPOI 是否支持复制工作表并将其插入到同一个工作簿中?
- c# - Fluent Validation:当验证器失败时使用另一个验证器
- java - 将一维数组移动到二维
- c# - 使用 Access 的 INSERT INTO 不起作用,没有任何错误?
- reactjs - react-vega 和 react-vega 工具提示
- ios - swift中的Alamofire InvalidURL