2

One of my tasks is to count the number of files that match a certain date pattern. Really what I need to do is loop through the directory, examine each file name, find the 2nd period in that file name, and then examine the next 4 characters to see if there is a match on the date string I am assembling.

November of 2012 would be represented as "1211". Using the first four characters after the 2nd period in the file names below, this would give us a hit on the first file name ("o.tt.121113150804") since it matches that pattern. I would count that file and then leave the other two alone.

The files below are just a sampling. They can be named in many different ways. They usually are just variations of the below 99% of the time. The fact that there are 2 periods and I need to check the 4 digits after the 2nd one is a definite constant though.

File names I need to check:

o.tt.121113150804
o.stpw.101209092541
i.rtat.120831045704
4

3 回答 3

4

这可以单独完成,ls但这也将匹配目录:

$ ls
i.rtat.120831045704  o.stpw.101209092541  o.tt.121113150804

$ ls *.*.1121*
o.tt.121113150804

然而find更强大和更灵活:

$ find . -maxdepth 1 -type f -iname "*.*.1211*"
./o.tt.121113150804

选项:

-maxdepth 1只看这个目录。

-type f只查找文件,不查找目录。

-iname使用模式匹配匹配任何内容的文件名,*因此*.*.1211*匹配任何内容,.然后是任何内容,然后是第二个.,然后是您的日期字符串和*其他任何内容。

编辑:

要计算匹配数,您可以通过管道传输wc -l并使用命令替换$(...)将值存储在变量中:

$ ls
i.rtat.120831045704  o.stpw.101209092541  o.tt.121113150804  
o.tt.121113150804c1  o.tt.121113150804c2

$ find . -maxdepth 1 -type f -iname "*.*.1211*" | wc -l
3

$ found=$(find . -maxdepth 1 -type f -iname "*.*.1211*" | wc -l)

$ echo $found
3
于 2012-12-14T18:40:47.233 回答
1

请注意,该模式*.*.1211*将匹配固定字符串前多于两个点的文件。例如,a.b.c.1211将匹配。

使用 bash,您可以编写:

shopt -s extglob
ls  +([^.]).+([^.]).1211*

如果您只想计算它们:

files=( +([^.]).+([^.]).1211* )
echo "${#files[@]} files matched"
于 2012-12-14T20:37:37.203 回答
0

@sudo_O 和 @glennjackman 回答了您的问题,但作为替代方案,如果您想一次获得所有日期的计数,您可以这样做

ls | awk -F'.' '{count[substr($3,1,4)]++} END{for (date in count) print date, count[date]}'
于 2012-12-14T22:50:57.300 回答