Android wrapper script to delete all files and folders in a directory except one

I am currently using rm -r / blaa / * to remove all folders and files in the blaa directory. I am looking for a way to delete all folders and files in the blaa directory except that the folder is named abc.

Any ideas?

+3


source to share


1 answer


On Linux:

There are many ways; however, I think the best way to do this is to simply use the " find

" tool .

find ! -iname "abc" -exec rm -rf {} \;

      

We can easily find and delete all files and folders that are not named "abc".

find      - to find files
! -iname  - to filter files/folders, the "!" means not
-exec     - to execute a command on every file
rm -rf    - remove/delete files -r for folders as well and -f for force
"{} \;"   - allows the commands to be used on every file

      

On Android:

Since you cannot use " rm -rf

", and when you use " rm -r

", it will delete the folder " .

" which will eventually delete everything.

I am assuming that you have "root" on your phone because you can use the Find tool.

find ! -iname "abc" | sed 1d | xargs rm -r

find      - to find files
! -iname  - to filter files/folders, the "!" means not
|         - pipe sends data to next command
sed       - replace text/output
"1d"      - removes first line when you do "find ! -iname" by itself
xargs     - runs commands after pipe
rm -r     - remove/delete files, "-r" for recursive for folders

      

Edit: Fixed and tested in Android



You can easily change this to suit your needs, please let me know if it helps!


Decision

... and the final hoorah ... This is what worked for the use case (helps to summarize the comments below as well):

find ! -iname "abc" -maxdepth 1 -depth -print0 | sed '$d' | xargs -0 rm -r;

      

Notes:

  • -depth

    - reverses the result (so don't remove the subdirs first
  • -maxdepth 1

    - kind of void, using -depth, but hey ... this only says the output contents of the current directory, not the sub-dirs (which are removed with the -r option anyway)
  • -print0

    and -0

    - splits into linear channels instead of white space (for drives with a space in the name)
  • sed "$d"

    - says to delete the last line (as a result it has now changed). The last line is just a period that would include a call to delete everything in the directory (and subs!)

I'm sure someone can tighten this up, but it works and was great teaching!

Thanks again Jared Burroughs (and the Unix community as a whole - the team!) - MindWire

+7


source







All Articles