Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何计算Unix中某个目录的文件名中出现的字符串/子字符串的实例数?_Linux_Bash_Unix_Directory_Filenames - Fatal编程技术网

Linux 如何计算Unix中某个目录的文件名中出现的字符串/子字符串的实例数?

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 或: 即使文件名包含换行符,

假设我当前的工作目录名为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
或:


即使文件名包含换行符,以下解决方案也有效:

$ touch  file1 file_dog filedog_1 dog_file
$ find . -maxdepth 1 -name '*dog*' -print0 | grep -zc .
3
工作原理:

  • find-maxdepth 1-名称“*dog*”-打印0

    这将查找当前目录中名称为
    dog
    的所有文件,并将它们打印在nul分隔列表中。由于nul字符是文件名中少数不允许的字符之一,因此这是安全的。如果需要不区分大小写的匹配(以便
    Dog
    也匹配),请将
    -name
    替换为
    -iname

  • grep-zc.

    这将读取nul分隔列表,并对行进行计数

    • -z
      告诉
      grep
      输入是nul分隔的

    • -c
      告诉
      grep
      抑制正常输出并计算匹配数

    • 告诉
      grep
      匹配任何内容


事实上,问题的标题意味着你也可以有狗咬狗的搭配(2个“dog”实例)-但建议的解决方案都不算作2。谢谢你,grep-c工作得很完美,也很简单!
$ touch  file1 file_dog filedog_1 dog_file
$ find . -maxdepth 1 -name '*dog*' -print0 | grep -zc .
3