我的linux系统中有sample.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
我想将sample.txt文件中的所有日期格式转换为YYYY-MM-DD
格式。
答案 0 :(得分:1)
使用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
答案 1 :(得分:0)
我不知道这是否是最佳方式,但这应该有效
awk '{print $6"-"$2"-"$3}' file.txt | sed 's/Jan/01/g; s/Feb/02/g; s/Mar/03/; s/Apr/04/g; s/May/05/g; s/Jun/06/g; s/Jul/07/g; s/Aug/08/g; s/Sep/09/g; s/Oct/10/g; s/Nov/11/g; s/Dec/12/g'