Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a peculiar problem I need help with. 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, but I suppose the solution will be similar to a Unix/Linux based problem

share|improve this question
up vote 3 down vote accepted

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"
share|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

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"
share|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
Good catch, thanks – DopeGhoti Jan 15 '14 at 18:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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