Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

In Linux, how do I delete all files in a directory that do NOT start with a pref (for example sess_*)?

share|improve this question

4 Answers 4

One solution is to pipe it through grep. For example:

cd /tmp ; ls -1 | grep -v sess_ | xargs rm -f

Another option is find (this excludes directories too):

find /tmp ! -name sess_\* ! -type d -exec rm -f {} \;
share|improve this answer
    
Why piping so much commands while 1 only can do the same job? –  Benoit Sep 16 '10 at 17:50
1  
Why not? If I didn't answer with it, I guarantee someone else would. There's multiple ways to do things in UNIX. –  Warner Sep 16 '10 at 17:51
    
Unnecessary use of resources (a pipe = a process + use of xargs ). You could use a shovel to hammer a nail but a hammer is much convenient don't you think? –  Benoit Sep 21 '10 at 12:04

I prefer find:

find ./ -type f \( \! -name 'sess_*' \) -exec rm {} \;

You might want to adjust depth in order to avoid recursion.

share|improve this answer

In the above

cd /tmp ; ls -1 | grep -v sess_ | xargs rm -f

the grep should be grep -v '^sess_*'

Other wise files such as ppp_sess_333 would be left behind.

share|improve this answer

Using Bash:

shopt -s extglob
rm !(sess_*)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.