If you have a series of subfolders (like from a to z) and want to run a command on each one of them (like rm *.pdf or ls *.pdf), how do you do that? The "manual" approach would be cd a, rm *.pdf, or ls *.pdf, cd .., cd b, ... That seems too complicated, so I believe there must be an easier approach.
|
|
||||
|
|
Try doing this (using bash, brace expansion & globs):
or
if your shell lack the brace expansion feature. Contrary to (Merci Stephane Chazelas for explanations) |
||||
|
|
For that particular example:
In any shell. In the general case, with Bourne-like shells, you could put the list of directories in
and then loop over it like:
Though of course you can do both in just one command:
The point is to use a subshell |
|||
|
|
|
Use find. Something like the following would find all folders (no more than two folders deep), and then execute
In my opinion the best thing to do with commands like these (you know, the ones with potential terrible consequences) is to prepend an 'echo' statement in front of the command you are trying to execute ... just to make sure it looks like what you want before you go pulling the trigger. |
|||||||||||
|
|
Well, assuming you want to remove all PDF files from the current directory and all other subdirectories beneath it, you would do something like
Two things to note: 1- I have added the 2- I highly encourage you to read the |
|||
|
|
|
find may be the best solution but it is easily possible in shell (bash):
or even easier
|
|||
|
|
|
If it is just one level of directories, you can simply do
That will delete all the pdf files in all the directories, but nothing else. In a case like this you may want to review the list of files selected before you do the delete. To do that try
And if the list is long enough to scroll off the screen, pipe it through a pager, eg
|
|||
|
|
|
I usually prefer xargs:
This has the benefit of adding grep or other manipulations in the middle of the pipeline, but has the disadvantage of not gracefully dealing with files that have spaces in the file or path name. |
|||||
|
|
Using a perl portable solution (for Unix-likes)
This will removes the subdirectories recursively under |
||||
|
|



