Skip to content
Advertisement

delete all folders and files within a linux directory except one folder and all contents inside that folder

I have a directory structure as :-

/usr/testing/member/
   ---> public--->folder1--->file1
           ----> file2
   ---> folder3:- contains files and folders
   ---> folder4:- contains files and folders
   ---> several files

I want to keep the public folder and all its contents (further folders and files within it) but want to delete everything else under the directory /usr/testing/member/. But that also means member folder is not deleted. Is there any shell script or command that can be used to achieve this exactly as i stated.

Advertisement

Answer

Here’s one way to do it:

(cd /usr/testing/member; find . -maxdepth 1 ( ! -name . -a ! -name public ) -exec echo rm -fr {} +)

That is: cd into /usr/testing/member, find all files and directories there, without going further below, and exclude the current directory (“.”) and any file or directory named “public”, and execute a command for the found files.

This will print what would be deleted. Verify it looks good, and then drop the echo.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement