0

The below command recursively deletes all but 104.tar file under /tmp/CURRENT folder.

find /tmp/CURRENT/ -type f ! -name '104.tar' -exec rm -rf {} + 

It however, does not recursively delete any sub-folders under /tmp/CURRENT.

if I give -type d it may help but I don't want a separate command. My requirement is to delete both files and folders with the same single command which I tried below but it did not help.

find /tmp/CURRENT/ -type f -type d ! -name '104.tar' -exec rm -rf {} + 

If I don't specify -type option at all, then the command delete the entire /tmp/CURRENT folder rather than its contents !

Note: MY OS is Sun Solaris Sparc.

Can you please suggest ?

1
  • Unless you know it is needed, avoid using rm -f. You only need -r to make it recursive and remove directories. Commented Jan 5, 2021 at 11:39

1 Answer 1

3

When you use -type f you are telling find to only consider files and nothing else. So it's normal that this does not delete directories. To avoid deleting /tmp/CURRENT/ itself, you could try a few things:

  1. If your find supports -mindepth (GNU find—the default on Linux systems—has this, I don't know what other find versions might support it), you can tell it to only look at things at least one level down:

    find /tmp/CURRENT/ ! -name '104.tar' -mindepth 1 
  2. Use a second ! operator to exclude it:

    find /tmp/CURRENT/ ! -path /tmp/CURRENT/ ! -name '104.tar' 
  3. Just use -path, and look for paths beginning with /tmp/CURRENT and followed by at least one more character:

    find /tmp/CURRENT/ -path '/tmp/CURRENT/?*' ! -name '104.tar' 

In all three cases, you can add -exec rm -r {} + to the end of the command to delete the matches.

However, note that these commands will delete everything except the specific file /tmp/CURRENT/104.tar. So if you have /tmp/CURRENT/dir1/104.tar or any other files named 104.tar in subdirectories, those will be removed. If this is not what you want, then please edit your question to clarify.

Of course, if all you want is to delete everything in /tmp/CURRENT except /tmp/CURRENT/104.tar, you don't need find at all. You can just run this in bash:

shopt -s extglob rm -r /tmp/CURRENT/!(104.tar) 
1
  • the second option worked fine !! Thank you Commented Jan 5, 2021 at 11:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.