2011-05-23 53 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])" 
相关问题