[英]Bash : extracting date from file
I am new to bash and I have a file like this : 我是bash的新手,我有一个这样的文件:
2012-11-22 11:36:55,909 1353551815756 1353551815909 0 true myapi 10 203051 203051:ShopDb:ShopDb
2012-11-22 11:37:00,292 1353551820146 1353551820292 0 true myapi 10 201897 201897:ShopDb:ShopDb
2012-11-22 11:38:01,824 1353551881672 1353551881824 0 true myapi 10 203051 203051:ShopDb:ShopDb
In a loop,line I want to extract date part (2012-11-22 11:36:55) convert to time-stamp and assign to a variable(or simply dis How to achieve this in bash ? 在一个循环中,我希望提取日期部分(2012-11-22 11:36:55)转换为时间戳并分配给变量(或者简单地说如何在bash中实现这一点?
You can also use date command, as one of the way to do it. 您也可以使用date命令作为其中一种方法。
while IFS=, read x y; do
date --date "$x" +%s
done < file.txt
+%s
converts it to the timestamp as you want. +%s
将其转换为您想要的时间戳。
$ while IFS=" ," read f1 f2 f3
> do
> echo $f1 $f2
> done < file
2012-11-22 11:36:55
2012-11-22 11:37:00
2012-11-22 11:38:01
By setting the IFS to a space and comma makes it easy to extract the 1st 2 fields in the while loop. 通过将IFS设置为空格并使用逗号可以轻松提取while循环中的前2个字段。
You can use GNU awk
to get the timestamps and capture them using a bash array: 您可以使用GNU awk
获取时间戳并使用bash数组捕获它们:
array=($(awk -F, '{ print mktime(gensub(/[:-]/," ","g",$1))}' file.txt))
Then you can iterate through them: 然后你可以遍历它们:
for i in "${array[@]}"; do echo "$i"; done
Results: 结果:
1353548215
1353548220
1353548281
Or simply select one to print; 或者只需选择一个进行打印; for example, to echo the second element: 例如,要回显第二个元素:
echo "${array[1]}"
Results: 结果:
1353548220
以下将为您提取日期:
awk 'BEGIN{FS="[ ,]"; OFS=" ";} {print $1, $2}' input_file
Use the cut
command: 使用cut
命令:
cut -c1-19 file
This will extract characters 1 through to 19 from each line. 这将从每一行中提取字符1到19。
To just retrieve the first line: 要检索第一行:
head -n 1 file | cut -c1-19
and to assign that to a bash variable: 并将其分配给bash变量:
myTime=$(head -n 1 file | cut -c1-19)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.