remove files other than selected

I wanna remove a set files other than some selected files.

Eg.

:rolleyes::rolleyes::rolleyes:

a directory contains n files like

test1.dat
test2.dat
test3.dat
test4.dat
out5.dat
out1.dat

i wanna remove all files which doesnot name like *test*

I want to use this in shell script, so please make sure that the cmd is independent of the working directory... !!! :wink:

Thanks

find path | while read N
do
    case `basename $N`
      dontDeleteMe | orMe | orMeEither )
          ;;
      * )
          rm "$N"
          ;;
    esac
done

got it..!!! :cool::D:D

ls /tmp/ | grep -v test | xargs -i ksh -c 'rm /tmp/"{}" '

can anyone lemme know if it is fool proof..!! :rolleyes:

/tmp is a shared directory, other people could have all kinds of stuff in there.

ksh:

rm !(*test*)

bash:

shopt extglob
rm !(*test*)

zsh (require setopt extendedglob):

rm  *~*test*

or:

rm ^*test*

But be careful :slight_smile:

Try this

rm out?

rm *out*

well.... . m not bothered about the directory.... i mentioned it as example.... !! :smiley:

none of them worked.... !!:mad:

thanks dude but that directory contains some files which might not have out in file name.. !!!

so i wanna delete all but *temp* files.... :stuck_out_tongue:

And your shell is?

find /path/to/files -type f ! -name '*test*' -exec rm {} \;

sh, ksh, bash

Strange,
could you post the output from your commands?

in ksh:

ls -l
ls -l !(*test*)

Did you try my find|case|rm approach?

-----------------------
$ ls
g_test1 test_11.dat test_3.dat test_6.dat test_9.csv test_dd.dat test_mrg1.dat
test_1.dat test_11.txt test_4.dat test_7.dat test_d.dat test_dt.txt test_script.ksh
test_10.csv test_2.dat test_5.dat test_8.csv test_d2.dat test_mrg.dat
$ ls -l !(*test*)
ls: 0653-341 The file !(*test*) does not exist.
-------------------------------------------------

EDIT:

The output is correct!
You don't have files that don't have the "test" pattern in the name!

Could you post the ksh version also, thanks!

print $KSH_VERSION

or

print ${.sh.version}

So:

rm -f !(*test*)

Use -f to suppress error messages (I don't know if ksh has the nullglob option :)).

both these cmds don't work on my machine

It's possible (you have ksh88 I suppose),
but the globbing I suggested should work.
You can always redirect/suppress the error messages
when no match is found.

This should work. Have you tryed it?