Monday, December 13, 2010

Delete all files except for some

Sometimes you want to delete all files in a folder, except for a few that match a pattern. Or you want to move them to a different folder. Using ls, awk and xargs, this can easily be accomplished in Linux or any *nix environment.

Let's say you have thousands of files in a folder and you wish to move all the files that are not from Oct2908 or Jul2707 into a folder called 'old'. Here's the one-liner that accomplishes this with ease:

ls | awk '!/Oct2908*/&&!/Jul2707*/' | xargs -i -t mv ./{} old/{}

First we call ls.

Then we pipe its output to awk, which matches all files that do not contain the pattern 'Oct2908*' and do not contain the pattern 'July 2707*'.

In turn, we pipe this to xargs, which calls mv on each file, moving it to the 'old' folder from the current folder.

Easy enough, and can be changed to any operation instead of mv, and any folder instead of 'old'.

2 comments:

  1. Do you know an easy / feasible way to make an alias for rm command so that instead of deleting the files, move them into a specific folder. So, in order something went wrong you would be able to recover the files.

    ReplyDelete
  2. You could try something like

    alias rm = 'mv -i \!~ ~/Trash'

    and then remember that it's always moved into a Trash folder. However, this will overwrite older files with the same name in the Trash folder.

    Other than that, it's safest to just set

    alias rm = 'rm -i'

    And deal with the confirmation that way.

    ReplyDelete