我正在尝试找出完成此任务的最佳方法,其中我有一个目录,其中包含多个具有不同文件名格式的文件,我需要解析那些在文件名中有日期的文件(格式) %F或YYYY-MM-DD)来自那些没有,然后使用for循环和case循环的混合迭代它们中的每一个,以隔离文件名中具有日期的文件和那些别。伪代码如下:
#!/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 :(得分: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。因为您似乎是新用户,如果您得到的答案可以帮助您,请记住将其标记为已接受,并且/或者给它一个+(或 - )作为有用的答案。
答案 1 :(得分: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])"