Showing posts with label text processing. Show all posts
Showing posts with label text processing. Show all posts

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