用于将日期和时间列转换为 .csv 中的 unix 时间戳的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8267595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script to convert a date and time column to unix timestamp in .csv
提问by Euan Hume
I am trying to create a script to convert two columns in a .csv file which are date and time into unix timestamps. So i need to get the date and time column from each row, convert it and insert it into an additional column at the end containing the timestamp.
我正在尝试创建一个脚本,将 .csv 文件中的两列(日期和时间)转换为 unix 时间戳。所以我需要从每一行中获取日期和时间列,将其转换并将其插入到包含时间戳的末尾的附加列中。
Could anyone help me? So far i have discovered the unix command to convert any give time and date to unixstamp:
有人可以帮助我吗?到目前为止,我发现了 unix 命令可以将任何给定的时间和日期转换为 unixstamp:
date -d "2011/11/25 10:00:00" "+%s"
1322215200
I have no experience with bash scripting could anyone get me started?
我没有 bash 脚本方面的经验,任何人都可以让我开始吗?
Examples of my columns and rows:
我的列和行的示例:
Columns: Date, Time,
Row 1: 25/10/2011, 10:54:36,
Row 2: 25/10/2011, 11:15:17,
Row 3: 26/10/2011, 01:04:39,
Thanks so much in advance!
非常感谢!
回答by bos
You don't provide an exerpt from your csv-file, so I'm using this one:
您没有提供 csv 文件的摘录,所以我正在使用这个:
[foo.csv]
2011/11/25;12:00:00
2010/11/25;13:00:00
2009/11/25;19:00:00
Here's one way to solve your problem:
这是解决您的问题的一种方法:
$ cat foo.csv | while read line ; do echo $line\;$(date -d "${line//;/ }" "+%s") ; done
2011/11/25;12:00:00;1322218800
2010/11/25;13:00:00;1290686400
2009/11/25;19:00:00;1259172000
(EDIT: Removed an uneccessary variable.)
(编辑:删除了一个不必要的变量。)
(EDIT2: Altered the date command so the script actually works.)
(EDIT2:更改了日期命令,以便脚本实际工作。)
回答by f4m8
Now two imporvements:
现在有两个改进:
First: No need for cat foo.csv, just stream that via < foo.csv into the while loop.
第一:不需要 cat foo.csv,只需通过 < foo.csv 将其流式传输到 while 循环中。
Second: No need for echo & tr to create the date stringformat. Just use bash internal pattern and substitute and do it inplace
第二:不需要 echo & tr 来创建日期字符串格式。只需使用 bash 内部模式并替换并就地进行
while read line ; do echo ${line}\;$(date -d "${line//;/ }" +'%s'); done < foo.csv
回答by Kent
this should do the job:
这应该可以完成这项工作:
awk 'BEGIN{FS=OFS=", "}{t=" "; "date -d \""t"\" +%s"|getline d; print ,,d}' yourCSV.csv
note
笔记
you didn't give any example. and you mentioned csv, so I assume that the column separator in your file should be "comma".
你没有举任何例子。你提到了csv,所以我假设你的文件中的列分隔符应该是“逗号”。
test
测试
kent$ echo "2011/11/25, 10:00:00"|awk 'BEGIN{FS=OFS=", "}{t=" "; "date -d \""t"\" +%s"|getline d; print ,,d}'
2011/11/25, 10:00:00, 1322211600