2017-10-20 37 views
2

如何使用正则表达式从文件路径和名称解析日期和时间?从文件名和路径分析日期和时间

我有存储在一个文件夹中这样

/home/user/folder/sub/2017-20-10/001/jpg/14/48/31[M][[email protected]][0].jpg 

基本上这告诉我,该图像从相机001采取2017-20-10 14:48:31

我想这个文件复制到一个新的位置,文件名称作为从路径+名称解析的日期和时间,所以新文件将是,即20172010144831.jpg

这样做的最佳方式是什么?我会假定正则表达式。这个表情会是什么样子?

+4

您试过的正则表达式是什么? –

+0

我什么也没得到。我无法弄清楚如何与/分割并获得第n部分 – Vili

+0

'YYYY-DD-MM'是日期的奇数格式。 – chepner

回答

3

理想情况下,您不必重复迭代的正则表达式和模式,但这至少是直接易懂的。

regex=/home/user/folder/sub/(....-..-..)/(.*)/jpg/(..)/(..)/(..).*\.jpg 
for f in /home/user/folder/sub/*/*/jpg/*/*/*.jpg; do 
    # Match against the regex, or skip to the next file 
    [[ $f =~ $regex ]] || continue 
    # The first capture group is the date. Strip the -. 
    d=${BASH_REMATCH[1]//-} 
    # The next three capture groups are the hour, minute, and second 
    t=("${BASH_REMATCH[@]:2:3}") 
    printf -v new_name '%s%s%s%s.jpg' "$d" "${t[@]}" # Put them all together 
done  
+1

我必须注意,这也将匹配非日期时间的路径,如'/ home/user/folder/sub/aaaa-a1-11/dd/jpg/01/a2/f3' – RomanPerekhrest

+0

正如你应该的。我最后一次更新答案时懒得用'[[:digit:]]'替换适当的'.'s。但即使这样也是过于宽容,因为它会允许像'2017-99-99'这样的无效日期。作为读者的练习,我不必写作一个适当限制性的正则表达式,或者在'd'和't'上添加额外的测试。 – chepner

0

find + bash解决方案具有特定正则表达式模式:

find . -type f -regextype posix-egrep \ 
-regex ".*/[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]+/jpg/[0-9]{2}/[0-9]{2}/[0-9]{2}.*.jpg$" \ 
-exec bash -c 'shopt -s extglob; 
     pat="/([0-9]{4})-([0-9]{2})-([0-9]{2})/[0-9]+/jpg/([0-9]{2})/([0-9]{2})/([0-9]{2})"; 
     [[ "$0" =~ $pat ]]; items="${BASH_REMATCH[@]:1:6}"; 
     cp "$0" "dest_dir/${items// /}.jpg"' {} \; 

  • dest_dir - 是您新位置