Recently I was faced with the task of deleting all the files/folders in a directory excluding those matching a specific pattern. So I cooked up a single-line unix command to do the work. Must it be only one line? I suppose not, but it's definitely cooler that way!
While the problem is pretty simple, I was a little surprised at how complex my solution ended up being. Here's the command I used; NOTE: this is a poor solution because it doesn't handle filenames containing line-feed characters (which didn't matter in my situation).
ls | grep -v PATTERN | xargs -n1 -IREPLACE rm -rf REPLACE
I did not use the "find" command because I do not want to recurse into folders matching PATTERN. For example, consider the following file structure:
file_foo.txt first_dir | +--> contents +--> ... foo_dir | +--> anotherfile.txt +--> morefiles.log foo_file.txt somefile.txt
Using pattern "foo" must only remove "first_dir" (and it's contents of course) and "somefile.txt" (not "anotherfile.txt" or "morefiles.log").
Question, are there better (more elegant and correct) ways to accomplish this?
It was recently brought to my attention that "find" may be a better option:
find * -maxdepth 0 ! -name PATTERN -print0 | xargs -0n1 rm -rf
This solution does correctly handle paths containing line-feed characters.