如何在linux/unix文本文件中更改日期格式 [英] How to change date format in linux/unix text file

查看:70
本文介绍了如何在linux/unix文本文件中更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的linux系统中有sample.txt文件.文件中存在的所有数据均采用以下日期格式

I have sample.txt file in my linux system.all the data that is present in my file are in the following date format

            Mon Apr 24 16:14:06 PDT 2017
            Tue Apr 25 13:31:25 PDT 2017
            Mon Apr 03 13:53:03 PDT 2017
            Sun Feb 05 16:19:27 PST 2017
            Sun Feb 05 17:51:42 PST 2017
            Sun Feb 05 18:16:21 PST 2017
            Sun Feb 05 19:17:33 PST 2017
            Sun Feb 05 21:14:23 PST 2017
            Sat Feb 04 10:39:33 PST 2017
            Sat Feb 04 10:46:52 PST 2017
            Sat Feb 04 14:35:27 PST 2017

我想将我的sample.txt文件中的所有日期格式都转换为 YYYY-MM-DD 格式.

I want to convert all this date format in my sample.txt file to YYYY-MM-DD Format.

推荐答案

使用 date -d 非常简单,例如

while read -r line; do 
    echo $(date -d "$line" +%Y-%m-%d); 
done < file.txt

输入文件

$ cat file.txt
            Mon Apr 24 16:14:06 PDT 2017
            Tue Apr 25 13:31:25 PDT 2017
            Mon Apr 03 13:53:03 PDT 2017
            Sun Feb 05 16:19:27 PST 2017
            Sun Feb 05 17:51:42 PST 2017
            Sun Feb 05 18:16:21 PST 2017
            Sun Feb 05 19:17:33 PST 2017
            Sun Feb 05 21:14:23 PST 2017
            Sat Feb 04 10:39:33 PST 2017
            Sat Feb 04 10:46:52 PST 2017
            Sat Feb 04 14:35:27 PST 2017

使用/输出示例

$ while read -r line; do echo $(date -d "$line" +%Y-%m-%d); done < file.txt
2017-04-24
2017-04-25
2017-04-03
2017-02-05
2017-02-05
2017-02-05
2017-02-05
2017-02-05
2017-02-04
2017-02-04
2017-02-04

这篇关于如何在linux/unix文本文件中更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆