Unix questions - Delete Files Except Certain Ones

This is Interesting: Free IT Magazines  
Home > Archive > Unix questions > November 2006 > Delete Files Except Certain Ones





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Delete Files Except Certain Ones
Will

2006-11-16, 1:30 am

Hi friends,

Suppose I have the following files in a directory:

abc
xyz.c
xyz.h
.......
totally 1000 files

1. How could I remove all files except those with .c at the end?

2. How about only except xyz.c and xyz.h??
(I don't want to move them to somewhere and put them back after
deleting all other files.)

Any smart command regarding rm ??

Thanks for your guidance in advance.

Will

Todd H.

2006-11-16, 7:29 am

"Will" <chickenwing2010@yahoo.com.hk> writes:

> Hi friends,
>
> Suppose I have the following files in a directory:
>
> abc
> xyz.c
> xyz.h
> ......
> totally 1000 files
>
> 1. How could I remove all files except those with .c at the end?
>
> 2. How about only except xyz.c and xyz.h??
> (I don't want to move them to somewhere and put them back after
> deleting all other files.)
>
> Any smart command regarding rm ??
>
> Thanks for your guidance in advance.


As in most things in unix, there is nearly nothing a properly crafted
application of the "find" command won't do.

Have a look at this:

$ find . \( \! -name "*\.c" \! -name "*\.h" -type f \) -print

Now, if that looks like the stuff you wanna kill, then replace print
with print0 to get it all on one neat line.

$ find . \( \! -name "*\.c" \! -name "*\.h" -type f \) -print0

and verify that these ARE FILES YOU NEVER WANT TO SEE AGAIN!

What that's doing is "i wana find files from teh current directory . ,
and I'm gonna built up an expression (it's not ending in .c and it's
not ending in .h and it's a file (f) rather than a directory or other
stuff). The and is implicit. And whatever you find that meets all my
picky criteria, print it out." The next command just says "print it
all out on one line. The backslashes are needed in most cases to
keep the stupid shell from interpreting the characters and sends them
on to find unmolested.

Next test it with xargs and a benign command, like friendly ole echo:

$ find . \( \! -name "*\.c" \! -name "*\.h" -type f \) -print0 | xargs -0 echo

Now and if that still looks like a list of stuff you don't wanna see
ever again, replace echo with /bin/rm -f:

$ find . \( \! -name "*\.c" \! -name "*\.h" -type f \) -print0 | xargs -0 /bin/rm -f


Use at your own risk. Understand it. You can do bad things in a
hurry with rm and find together, but you can also do wonderful things
such as ... exactly what you want.

Good luck!

Best Regards,
--
Todd H.
http://www.toddh.net/
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com