Rm all files but two

I am on Solaris using bash profile.

I wish to delete all files under /tmp/data/ except output.txt and hello.txt

I prefer using the one line command like rm

I tried this command but it is failing.

rm -rf /tmp/data/* !(@(output.txt|hello.txt))
bash:  !: event not found.

Can you please suggest. I would preferably want a command that works on both Linux and Solaris.

Turn on extended globbing first:

shopt -s extglob

Still, I cannot see it working. Below is the error.

bash-3.2$ shopt -s extglob
 bash-3.2$ rm -rf /tmp/data/* !(@(output.txt))
rm: cannot read directory enav/output: Permission denied
rm: Unable to remove directory enav: File exists
rm: Unable to remove directory hsperfdata_u543267: Permission denied
rm: Unable to remove directory hsperfdata_vbarne: Permission denied

Strangely along with the error the /tmp/data/ folder itself gets deleted.

I think your pattern is wrong.
Should be

ls -ld /tmp/data/!(output.txt|hello.txt)

If not 100% confident, test with ls -ld first, then run rm -rf .

1 Like

You are right !! The syntax was incorrect. This works :slight_smile: