2011-05-23 47 views
1

我想弄清楚完成此任務的最佳方法,其中我有一個具有多種文件的目錄,其文件名格式各不相同,我需要解析將那些文件名中有日期的文件(格式爲%F或YYYY-MM-DD)與那些不包含文件名的文件進行比較,然後使用for循環和case循環的混合來遍歷每個文件以隔離在文件名中有日期的文件和沒有文件名的文件之間。僞代碼如下:bash:僅顯示文件名中包含日期的文件

#!/bin/bash 
files=`ls` 
for file in $files; do 
    # Command to determine whether $file has a date string 
    case (does variable have a date string?) in 
    has) # do something ;; 
    hasnt) # do something else ;; 
    esac 
done 

什麼是插上的評論最好的命令,並執行基於關閉命令,一個case語句那麼最簡單的方法?

+0

是和案件的要求?爲什麼不使用find? – matchew 2011-05-23 15:02:45

回答

5

鑑於你的原代碼,你可以做

files=`ls` 
for file in $files; do 
    # Command to determine whether $file has a date string 
    case ${file} in 
    *2[0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]*) 
     # note that this date-only matching reg-exp is imperfect 
     # it will match non-dates like 2011-19-39 
     # but for cases where date is generated with date %F 
     # it will work OK 
     : # do something 
    ;; 
    *) # do something else ;; 
    esac 
done 

或者作爲@matchw建議,您可以使用該模式在找到

find . -type f -name '*2[0-9][0-9][0-9]-[0-1][0-9]-[0-3]-[0-9]*' -print0 \ 
    | xargs yourCommand 

我希望這有助於。

P.S.因爲你似乎是一個新用戶,如果你得到一個可以幫助你的答案,請記住將它標記爲已接受,並且/或者給它一個+(或 - )作爲有用的答案。

+0

如果你打算使用'find | xargs',那麼使用'-print0'選項'find'和'-0'選項來''xargs',這樣你就可以用「不友好的」字符(例如空格)英寸 – 2011-05-23 15:16:32

+1

以上匹配說2011-19-39 – 2011-05-23 15:17:26

+0

非常好,謝謝你用僞碼示例! – Scott 2011-05-23 15:25:46

1

使用grep與正則表達式

喜歡的東西

grep -E "20[0-9]{2}\-(0[1-9]|1[0-2])\-([0-2][0-9]|3[0-1])" 

如。

echo "FOO_2011-05-12" | grep -E "20[0-9]{2}\-(0[1-9]|1[0-2])\-([0-2][0-9]|3[0-1])" 
相關問題