Bash – Copy subfolders containing at least n files

bashfile-copyfind

I have a folder root_folder containing a lot of subfolders. Each of these subfolders contains a small number of files (between 1 and 20) and I want to copy all the subfolders containing at least 5 files into another folder new_folder. I have found how to print the folders that interest me: https://superuser.com/questions/617050/find-directories-containing-a-certain-number-of-files but not how to copy them.

Best Answer

You can do a for loop on the find result and copy the folder with -R :

IFS=$'\n'
for source_folder in "$(find . -maxdepth 1 -type d -exec bash -c "echo -ne '{}\t'; ls '{}' | wc -l" \; |  
awk -F"\t" '$NF>=5{print $1}');" do 
  if [[ "$source_folder" != "." ]]; then 
    cp -R "$source_folder" /destination/folder
  fi
done
Related Question