bash解析文件名 [英] bash parse filename

查看:84
本文介绍了bash解析文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash中有什么方法可以解析该文件名:

Is there any way in bash to parse this filename :

$file = dos1-20120514104538.csv.3310686

转换为像$date = 2012-05-14 10:45:38$id = 3310686这样的变量?

into variables like $date = 2012-05-14 10:45:38 and $id = 3310686 ?

谢谢

推荐答案

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

All of this can be done with Parameter Expansion. Please read about it in the bash manpage.

$ 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

组合PE以新格式重新组合日期.您还可以将日期与GNU日期一起解析,但这仍然需要重新安排日期,以便可以对其进行解析.在当前格式下,这就是我的处理方式:

Combine PEs to put date back together in a new format. You could also parse the date with GNU date, but that would still require rearranging the date so it can be parsed. In its current format, this is how I would approach it:

$ 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

这篇关于bash解析文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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