Delete all file except some in bash, without cd to the directory?

2

I need to make a daily cleanup in a download directory.

I have saw this question and tested the answer

rm !("test 1"|"test 4")

It work great, but require to have cd to the directory before. Since my app need to be two direcltory higher in many part, I d like to don t have to make something like

cd /app/download
rm !("test 1"|"test 4")
cd ../..

I have tried

rm !("./app/download/test 1"|"./app/download/test 4")

But well, it delete the content of the higher directory, not download/

DrakaSAN

Posted 2013-09-19T08:18:14.797

Reputation: 370

Answers

2

You were almost there:

shopt -s extglob   # ← Only needed if you haven't enabled it yet
rm ./app/download/!("test 1"|"test 4")

The !(…) will be expanded with the full path to all files except the ones in !(…). Since you prefix the arguments to rm with the path ./app/download/, no other files higher than that directory will be deleted.

slhck

Posted 2013-09-19T08:18:14.797

Reputation: 182 472