Create a folder "Photo" inside all directories recursively
I have a bunch of folders and I want to loop over all those folders and in each folder create another folder named "Photo"
F1
--F11
----F111
----F112
--F12
I want to have:
F1
--Photo
--F11
----Photo
----F111
------Photo
----F112
------Photo
--F12
----Photo
You can achieve it using a single find
call.
find . -name 'Photo' -prune -o -type d -exec mkdir {}/Photo \;
The part -name 'Photo' -prune -o
tells to not recurse to existing (and newly created) Photo
directories: If the found file (or directory) has the name Photo
, stop processing it (-prune
). In the other case (-o
), continue with directories (-type d
) and execute (-exec
) the command.
You could pass find
results to while
instead of for
since this way it won't break if the filenames have spaces
First cd to the directory F1
, then do:
find -type d | while read dir ; do mkdir "$dir"/Photo ; done
If the directory exists, mkdir
will just refuse to create it, so no problem there...
If your directory names could contain newlines, or other exotic strangeness, use this which can deal with arbitrary names:
find -type d -print0 | while IFS= read -r -d '' dir ; do mkdir "$dir"/Photo ; done
Thanks to @terdon for help with this :)
From the directory just above F1 run this script:
The purpose of the script is to avoid having redundant photo directories created under photo directories.
Also, it's design to prevent accidentally running it from a wrong location such as the user's root directory, whereas it wouldn't see the F1
directory and mistakenly create hundreds of photo directories in the wrong palaces.
Also, it was my intentions to make an easy to follow script so the user could customize it.
#!/bin/bash
while IFS= read -r -d '' i;
do
if [[ ! -d $i/Photo ]]; then
# Filter to skip folders named Photo
thisfolder="$(echo $i | sed "s/.*\///")"
if [[ ! $thisfolder == "Photo" ]]; then
mkdir "$i/Photo"
fi
fi
done < <(find F1 -type d -print0)
Script Updated:
- Changed the lower case
p
inphoto
to upper case. - Added support for non-stander filesnames (with suggestions from Terdon).