简体   繁体   中英

echo the output of a ls command with less files than n

I have 400 folders with several files inside, I am interested in:

  1. counting how many files with the extension .solution are in each folder, and
  2. then output only those folder have less than 440 elements

The point 1) is easy to get with the command:

for folder in $(ls -d */ | grep "sol_cv_");
do
    a=$(ls -1 "$folder"/*.solution | wc -l); 
    echo $folder has "${a}" files;
done

But is there any easy way to filter only the files with less than 440 elements?

This simple script could work for you:-

 #!/bin/bash

 MAX=440

 for folder in sol_cv_*; do
     COUNT=$(find "$folder" -type f -name "*.solution" | wc -l)
     ((COUNT < MAX)) && echo "$folder"
 done

The script below

counterfun(){
count=$(find "$1" -maxdepth 1 -type f -iname "*.solution" | wc -l)
(( count < 440 )) && echo "$1"
}
export -f counterfun
find /YOUR/BASE/FOLDER/ -maxdepth 1 -type d -iname "sol_cv_*" -exec bash -c 'counterfun "$1"' _ {} \;
#maxdepth 1 in both find above as you've confirmed no sub-folders

should do it

Avoid parsing ls command and use printf '%q\\n for counting files:

for folder in *sol_cv_*/; do
    # if there are less than 440 elements then skip
    (( $(printf '%q\n' "$folder"/* | wc -l) < 440 )) && continue
    # otherwise print the count using safer printf '%q\n'
    echo "$folder has $(printf '%q\n' "$folder"*.solution | wc -l) files"
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM