Adsense Leaderboard Ad

10.27.2013

Run rm command but exclude one file


Question sent in by Trsih from Ohio:

Q: Is there anyway to run the rm command (or rm -rf) and exclude one file?

A: There is no exclude option for the rm command in Linux. You can however string some commands together in order to make this happen.

For example, let's say you had a directory and you wanted to delete all the files except for a file call important.txt.  You could try something like this:

rm -rf `find . -name "*" ! -name "important.txt"`

or

find . ! -name "important.txt" -exec rm -rf {} \;


There are many ways to accomplish the same thing in Linux. I am sure people can come up with at least 10 different way to do this. Please post in the comments if you have a more efficient way of doing this.
NOTE: BE CAREFUL WITH rm -rf IT CAN BE DANGEROUS.

4 comments:

  1. Hi,

    I need command for exclude multiple file with rm -rf

    Thanks,
    Mohan.

    ReplyDelete
  2. You can do something like this:

    find . ! \( -name "file1" -o -name "file2" \) -exec rm -vf {} \;

    ReplyDelete
    Replies
    1. Great! I need that! Thx Savona! :-)

      Delete