0

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?

gatorback
  • 1,384
  • 23
  • 48

2 Answers2

1
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`

Kusalananda
  • 333,661
  • @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 05 '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 05 '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 05 '18 at 18:12
  • @gatorback I've added a reference to a quite long answer I've written previously on this topic. – Kusalananda May 05 '18 at 18:16
-1

I suppose just do :

rm -rf `find /myPhotorec -name "*" | grep  -v "44c9ea3abbd24"`
Kusalananda
  • 333,661
Dzango
  • 29
  • 2
    This would perform the grep on filenames, not the contents of the files. – Kusalananda May 05 '18 at 05:51
  • It would also not delete anything in any folder whose name contained 44c9ea3abbd24, and it would have issues with filenames containing embedded newlines. See https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice – Kusalananda May 05 '18 at 06:00