Linux 如何计算Unix中某个目录的文件名中出现的字符串/子字符串的实例数?
假设我当前的工作目录名为my_dir,其中有几个不同的文件:Linux 如何计算Unix中某个目录的文件名中出现的字符串/子字符串的实例数?,linux,bash,unix,directory,filenames,Linux,Bash,Unix,Directory,Filenames,假设我当前的工作目录名为my_dir,其中有几个不同的文件: file1 file_dog filedog_1 dog_file 我如何计算“dog”在我的目录中出现(应该是3)的实例数 谢谢大家! 您可以使用grep中的-c选项 grep -c: Suppress normal output; instead print a count of matching lines for each input file. ls -1 | grep -c dog 或: 即使文件名包含换行符,
file1
file_dog
filedog_1
dog_file
我如何计算“dog”在我的目录中出现(应该是3)的实例数
谢谢大家! 您可以使用grep中的-c选项
grep -c:
Suppress normal output; instead print a count of matching lines for each input file.
ls -1 | grep -c dog
或:
即使文件名包含换行符,以下解决方案也有效:
$ touch file1 file_dog filedog_1 dog_file
$ find . -maxdepth 1 -name '*dog*' -print0 | grep -zc .
3
工作原理:
这将查找当前目录中名称为find-maxdepth 1-名称“*dog*”-打印0
的所有文件,并将它们打印在nul分隔列表中。由于nul字符是文件名中少数不允许的字符之一,因此这是安全的。如果需要不区分大小写的匹配(以便dog
也匹配),请将Dog
替换为-name
-iname
这将读取nul分隔列表,并对行进行计数grep-zc.
告诉-z
输入是nul分隔的grep
告诉-c
抑制正常输出并计算匹配数grep
告诉
匹配任何内容grep
$ touch file1 file_dog filedog_1 dog_file
$ find . -maxdepth 1 -name '*dog*' -print0 | grep -zc .
3