Skip to content
Advertisement

Find subdirectory and remove files not containing a specific string LINUX

Given a main path ./class and within class are subdirectories student1,student2,student3student100. within these subdirectories are other sub-directories history,geography,Math. Each of these subdirectories have hundreds of files in them. I want to KEEP all files that have a string pass in Math ONLY without affecting files in other subjects. So far I can cd to Math and do this:

find . -type f -print0 | xargs --null grep -Z -L 'pass' | xargs --null rm

But it is ineffective to cd to Mathin each of the100 subdirectories and rm unwanted files.

How can one grep only Mathand execute the code above?

Advertisement

Answer

the following should do the trick

for i in `find . -type d -name *Math* -exec find {} -type f -not -name *pass* ;`; do rm $i ; done
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement