How to print only one occurence with echo or printf in a for loop

Viewed 95

I have a folder TEST with some files (with the occurence abc) I want to delete. I use :

for filename in TEST/*; do  
   if [ -f "$filename" ]; then 
       if [[ "$filename" == *abc* ]]; then  
             rm $filename  && echo "The files $filename are well deleted" ; 
             else printf  "The files were already deleted" ; 
       fi; 
   fi; 
done

What I want, is to print the "The files were already deleted" only once . For example, after removing the files with the occurence abc , if it remains 4 files inside the folder TEST , that will print the sentence "The files were already deleted" 4 times, and not one like I would like to.

Any idea?

1 Answers

I don't understand why you are using a loop for this.

rm TEST/*abc*

should do it, though it won't report each file. It'll maybe complain about directories that match.

If you need the report -

found=0
while IFS= read -rd '' f
do rm $f && echo "deleted '$f'"
   found=1
done < <( find TEST/ -name '*abc*' -type f -print0 )
(( found )) || echo "The files were already deleted"
Related