Recovered files are stored in /myPhotorec.

The goal is to recursively grep through each file and if it does NOT have the string "44c9ea3abbd24" in the file contents (not the filename), then delete it. The target was a python .py file and is randomly renamed by the file recovery name.

If this can not be done, then maybe the file containing can be copied to a directory /filtered?

  • string 44c9ea3abbd24 or word 44c9ea3abbd24? – cuonglm May 5 '18 at 5:20
  • Text files that need to be retained / sorted having the string 44c9ea3abbd24 – gatorback May 5 '18 at 5:49
  • 1
    Is the string in the content of the file, or in the filename? – Kusalananda May 5 '18 at 5:51
  • 1
    @Kusalananda Thanks for the ver good question. content of the file. – gatorback May 5 '18 at 13:24
find /myPhotorec -type f ! -exec grep -qF '44c9ea3abbd24' {} ';' -print -delete

This would find all regular files in or under the /myPhotorec directory, test whether they contain the given string (in the content of the file), and for each file that does not contain the string, display the pathnames and delete them.

If your find does not support -delete, then replace that part with -exec rm {} +.

If you want to manually confirm each deletion, change -delete to -ok rm {} ';'.

Regarding find ... -exec ...: Understanding the -exec option of `find`

  • @Kusalanananda It would be pedagogically helpful if two additional code snippets were added to the explanation: 1) the find the filenames sans target string and pipe into 2) delete command. Preliminary test results of your solution look good on OS X. – gatorback May 5 '18 at 13:34
  • @gatorback Piping the results of find into anything is not generally a good idea. One could obviously use the non-standard -print0 with find and then pipe that into xargs -0 rm (where -0 is likewise non-standard), but this has absolutely no benefit over using e.g. -exec rm {} + as in my answer. – Kusalananda May 5 '18 at 13:38
  • My mistake, you did not use pipe in your solution. I am trying to dissect the solution because my understanding of the find and exec commands is very basic. Breaking it down according to your thought process would accelerate the learning process – gatorback May 5 '18 at 18:12
  • @gatorback I've added a reference to a quite long answer I've written previously on this topic. – Kusalananda May 5 '18 at 18:16

I suppose just do :

rm -rf `find /myPhotorec -name "*" | grep  -v "44c9ea3abbd24"`

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.