This entry is a quick tip about Bash shell.
Many times I want to remove (rm
), copy (cp
), move (mv
) or do other things (cat
, head,
etc.) to all files in a directory, except to a particular one or ones. If there are few files in a directory, it is not a big problem. But if you have 20 or more files, it can be a waste of time, mainly if you have to repeat the process many times. So, looking for a simple way to do that, I found this discussion in StackOverflow and this other link in Bash Hackers wiki.
Basically, you have to add the following line in the .bashrc file:
shopt -s extglob
This line will extends regexes
and will able you to use patterns or lists in commands.
For example, if you want to remove all files, except one, you can use:
rm !(theFileIWannaSave)
Or, for a group of files with the same pattern:
cat !(pattern*)
To skip a list of files, you should use the pipe ( | ) as the separator:
mv !(firstFile | secondFile | thirdFile) ../
And there are other options, as you can check in the Bash hacker wiki link.