2017-10-20 36 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 - 是您新位置