首页 > 解决方案 > Count of no of files which contain a particular string in its name

问题描述

I am simply trying to count how many files in a given directory contain a particular string anywhere in its name ( not the total occurance of string ) & ignore hidden directories

Example

>> ls -a
.hidden_dir
string1.nfo 
'string1 - string.exe' 
string5-.mkv

Here , ignoring the hidden directory , 3 files contain the letter "string" anywhere in their name , so i expect grep to return 3 correctly but its not working & returns 0 instead. Here's the grep command i am using -

grep --exclude-dir=".*" -l "string" * | wc -l

标签: grepfind

解决方案


You can use this pure bash code:

arr=(*string*) && printf '%d\n' "${#arr[@]}"

Details:

  • arr=(*string*): Find all entries in current directories that have name string anywhere and put them into array arr
  • printf '%d\n' "${#arr[@]}": Print length of array arr

Based on comments below here is a find solution:

find . -type f -maxdepth 1 -iname '*string*' ! -name '*.txt' \
-exec bash -c 'printf "%s\n" "${@//*/.}"' _ {} + | wc -l

推荐阅读