【发布时间】:2013-09-05 20:20:22
【问题描述】:
在我的情况下,有可能获取 abb_Timestamp.csv 或 ABC_TIMESTAMP.CSV 之类的文件。我正在使用ls -l | grep ABC* | wc -l。无论情况如何,我都想要文件的数量。即使我得到大写字母的文件,我也应该得到计数,即使我得到小写字母,我也应该得到 unix 中的计数。请建议。
【问题讨论】:
在我的情况下,有可能获取 abb_Timestamp.csv 或 ABC_TIMESTAMP.CSV 之类的文件。我正在使用ls -l | grep ABC* | wc -l。无论情况如何,我都想要文件的数量。即使我得到大写字母的文件,我也应该得到计数,即使我得到小写字母,我也应该得到 unix 中的计数。请建议。
【问题讨论】:
解析ls 的输出被认为是bad practice。你可以使用find:
find . -iname 'ABC*' | wc -l
man find:
-iname pattern
Like -name, but the match is case insensitive. For example, the
patterns `fo*' and `F??' match the file names `Foo', `FOO',
`foo', `fOo', etc. In these patterns, unlike filename expan‐
sion by the shell, an initial '.' can be matched by `*'. That
is, find -name *bar will match the file `.foobar'. Please note
that you should quote patterns as a matter of course, otherwise
the shell will expand any wildcard characters in them.
正如评论中的 Johnsyweb 所述,find 默认会递归到子目录中。为避免这种情况,您可以提供-maxdepth 1:
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc‐
tories below the command line arguments. -maxdepth 0
means only apply the tests and actions to the command line
arguments.
【讨论】:
-maxdepth 1 提供给find,否则会递归到子目录中,而问题中的命令不会。
人 grep:
$ echo "FOO" | grep foo
$ echo "FOO" | grep -i foo
FOO
$ echo "FOO" | grep -c -i foo
1
【讨论】:
使用 awk。 使用 csv/CSV 搜索所有文件并计算点击次数,只需一个 awk。
ls -l | awk 'tolower($9)~"csv" {a++} END {print a}'
【讨论】: