A project I was working on required adding a default index.html file into each subdirectory in a directory. This ensured an appropriate response was given when someone browsed to any directory on the web server. The command I came up with to copy a file into all subdirectories was:
ls -d */ | xargs -n 1 cp -i index.html
The command breaks down like this. Where Index.html is the file that will be copied. The ‘ls -d */’ command retrieves a list of directories in the current directory. The list is piped ‘|’ into xargs to execute the copying process. Unfortunately this command was not as robust as I was hoping. It doesn’t work with directories that have spaces in the name. It also only copies the file into the immediate subdirectories. Noting those issues I refined the command. The resulting modified command will copy a file into all subdirectories recursively.
ls -R | grep ":" | sed "s/^.://" | sed "s/://" | xargs -n 1 cp -n index.html
This command also copies the index.html file. ‘ls -R’ retrieves a list of all files and directories recursively from the current folder. The ‘grep “:”‘ portion locates all the directories since they each end with a colon “:”. Then the ‘sed “s/^.://”‘ section removes the reference to the current directory “.” in the returned directory list. The ‘sed “s/^.://”‘ portion cleans off the trailing colons “:” from each directory entry. The resulting cleaned list of directories is piped into the xargs command to copy the file into each one.
So give it a go, it could save you a bit of time and hassle now that you can copy a file into all subdirectories.
I created this post using these resources: