Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

Using Bash:

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

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

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
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

Your Answer


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