3

I have a large batch of .docx files where a certain number of them are junk. I know how to identify these files from the file command, as they contain the phrase "Number of Words: 161" from the output of file cmd. I need to delete these files. I have the following so far,

file * | grep "Number of Words: 161"

which gives an output similar to

19028409: CDF V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: author, Template: Normal, Last Saved By:  , Revision Number: 2, Name of Creating Application: Microsoft Office Word, Last Printed: Mon Dec 13 13:21:00 2010, Create Time/Date: Wed Dec 12 22:39:00 2012, Last Saved Time/Date: Wed Dec 12 22:38:00 2012, Number of Pages: 1, Number of Words: 161, Number of Characters: 923, Security: 0

where the filename is 19028409

How can I delete all instances of these files? I should also add that I am running this from the MAC OS X terminal

4

Try this:

for f in ./*docx; do file "$f" | grep -q "Number of Words: 161" && rm "$f"; done

This will loop through all .docx files in the current directory and delete them if the exit code of grep is 0. grep will return 0 if the current file matches the string you searched for. The -q is just to suppress output.

To make sure this works as expected, run it with printffirst:

for f in ./*docx; do 
 file "$f" | grep -q "Number of Words: 161" && 
   printf "%s\n" "rm $f"
done
| improve this answer | |
  • This worked for me thanks, I also like that you added the sanity check with printf :). I made one small alteration since my files don't actually end with docx, so I just used * – user251482 Jan 15 '14 at 18:17
  • @user251482 fair enough, I just used *docx to skip directories. – terdon Jan 15 '14 at 18:19
0

So long as no filenames have colons in them:

IFS="\n" for f in $(file * | grep "Number of Words: 161" | sed 's/:.*$//'); do
 rm "$file"
done
| improve this answer | |
  • Thanks, it's giving me "syntax error near unexpected token 'do'" – user251482 Jan 15 '14 at 17:57
  • I rolled back your edit because there is a need to use file. The string Number of Words: 161 is in the output of file ot in the .docx document itself. – terdon Jan 15 '14 at 18:18
0

If you didn't find the answer, how about:

for i in `file *|grep "Number of Words"|awk -F ":" '{print $1}'`
do
rm $i
done
| improve this answer | |
  • Note, put back quotes from the word file to the end of the line... – user330440 Jan 8 '19 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.