Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to remove all files except specifed ones?

Status
Not open for further replies.

volcano

Programmer
Aug 29, 2000
136
HK
Dear web friends,

I would like to write a shell script which is used to remove all files in all subdirectories (one-level subdirectory only) except that the abc.txt and def.txt files in those subdirectories can't be deleted. Do u have any idea?

Thank you very much!

Volcano
 
How about:
find . -type f -print | grep -v abc.txt | grep -v def.txt | xargs rm
 
Volcano:

another way: find everything not named abc.txt and def.txt and remove it:

find . -type f ! \( -name 'abc.txt' -o -name 'def.txt' \) -print|xargs rm

Regards,


Ed
 
Thank you for your replies!

Your commands works well. However I find that the command will delete my script which contains this command too!

My directory structure is like that:
There is a parent directory named "parent1". It contains my script which is used to clear directories. And there are some subdirectories under "parent", namely "child1" and "child2". There are files named "emailadr.txt" and "faxno.txt" (which should not be deleted), as well as other unused files. My target is to deal with "child1" and "child2" directories only. Just leave "parent" directory untouched.

So do u have any idea?
Thanks again~~
 
Volcano:

I don't want to elaborate on the obvious, but why not search only the directories you care about:

# untested

find /pathtoparrent/parent/child1 /pathtoparrent/child2 -type f ! \( -name 'abc.txt' -o -name 'def.txt' \) -print|xargs rm

Regards,

Ed

 
Thanks olded for your prompt reply!

In my real case, there is nearly a hundred sub-directories under the "parent" directory (and the number may grow in the future, but each new subdirectory must have abc.txt and def.txt~); therefore that FIND statement seems not appropriate to my situation..therefore I want to clear those unknown amount of sub-directories but leave "parent" directory untouched.

Hope that u can understand my English :)

Thanks!
 
To expand on my earlier post:
find . -type f -print | grep child | grep -v abc.txt | grep -v def.txt | xargs rm
 
To not remove your script as well, here's a hack on the find command previously posted by olded...

find . -type f ! \( -name 'abc.txt' -o -name 'def.txt' -o -name 'myScript.sh' \) -print|xargs rm

I just added another file (your script) to the list of files not to search for.

However, this is untested.
 
#!/bin/sh
for file in `find .`
do case $file in *DONOTDELETE) continue;; esac
rm -rf $file
done
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top