bash解析文件名

puf*_*fos 4 bash parsing tokenize

在bash中有什么方法可以解析这个文件名:

$file = dos1-20120514104538.csv.3310686

变成$date = 2012-05-14 10:45:38和变量$id = 3310686

谢谢

koj*_*iro 13

所有这些都可以通过参数扩展来完成.请在bash联机帮助页中阅读.

$ file='dos1-20120514104538.csv.3310686'
$ date="${file#*-}" # Use Parameter Expansion to strip off the part before '-'
$ date="${date%%.*}" # Use PE again to strip after the first '.'
$ id="${file##*.}" # Use PE to get the id as the part after the last '.'
$ echo "$date"
20120514104538
$ echo "$id"
3310686
Run Code Online (Sandbox Code Playgroud)

将PE组合在一起以新格式重新组合日期.您还可以使用GNU日期解析日期,但仍需要重新排列日期以便对其进行解析.在目前的格式中,这就是我接近它的方式:

$ date="${date:0:4}-${date:4:2}-${date:6:2} ${date:8:2}:${date:10:2}:${date:12:2}"
$ echo "$date"
2012-05-14 10:45:38
Run Code Online (Sandbox Code Playgroud)