Does any one have a template shell script for doing something with
ls for a list of directory names and looping through each one and doing something?
I'm planning to do
ls -1d */ to get the list of directory names.
Edited not to use ls where a glob would do, as @shawn-j-goff and others suggested.
Just use a
You can replace the
For example, to rename all the
Or even better, if you are using Bash you can use Bash parameter expansions rather than spawning a subshell:
Using the output of
There are two very good ways of iterating over files. Here, I've used simply
The first is to use the shell's native globbing features.
The shell expands
If you want to go recursively into subdirectories, then this won't do unless your shell has some extended globbing features (such as
The syntax of the
If you have GNU Parallel http://www.gnu.org/software/parallel/ installed you can do this:
To rename all .txt to .xml:
Watch the intro video for GNU Parallel to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ
For files with spaces in you will have to make sure to quote the variable like:
or, you can change the input field separator (IFS) environment variable:
Finally, depending on what you're doing, you may not even need the ls:
Why not set IFS to a newline, then capture the output of
(In testing I was having trouble setting IFS to
E.g. (assuming desired
This is especially handy on OS X, e.g., to capture a list of files sorted by creation date (oldest to newest), the
This is how I do it, but there are probably more efficient ways.