I know how to loop through all the files in a directory, for example:
for i in *
do
<some command>
done
But I would like to go through all the files in a directory, including (particularly!) all the ones in the subdirectories. Is there a simple way of doing this?
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).
Copying Directories with cp Command To copy a directory, including all its files and subdirectories, use the -R or -r option. The command above creates the destination directory and recursively copy all files and subdirectories from the source to the destination directory.
To copy a directory with all subdirectories and files, use the cp command.
Copy a Directory and Its Contents ( cp -r ) Similarly, you can copy an entire directory to another directory using cp -r followed by the directory name that you want to copy and the name of the directory to where you want to copy the directory (e.g. cp -r directory-name-1 directory-name-2 ).
The find
command is very useful for that kind of thing, provided you don't have white space or other special characters in the file names:
For example:
for i in $(find . -type f -print)
do
stuff
done
The command generates path names relative from the start of the search (the first parameter).
As pointed out, this will fail if your filenames contain spaces or some other characters.
You can also use the -exec
option which avoids the problem with spaces in file names. It executes the given command for each file found. The braces are a placeholder for the filename:
find . -type f -exec command {} \;
find
and xargs
are great tools for recursively processing the contents of directories and sub-directories. For example
find . -type f -print0 | xargs -0 command
will run command
on batches of files from the current directory and its sub-directories. The -print0
and -0
arguments avoid the usual problems with filenames that contain spaces, quotes or other metacharacters.
If command
just takes one argument, you can limit the number of files passed to it with -L1
.
find . -type f -print0 | xargs -0 -L1 command
And as suggested by alexgirao, xargs
can also name arguments, using -I
, which gives some flexibility if command
takes options. -I
implies -L1
.
find . -type f -print0 | xargs -0 -Iarg command arg --option
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With