Add a file to every subdirectory recursively

Posted on

I was creating a directory structure for a new project where many of the folders were initially empty. Since you can’t check empty directories into git, I needed to iterate through all of the directories I had just created and add an empty placeholder file.

My command line skills aren’t too sharp, but after enough Googling, I was able to build something that worked:

find . -type d | grep -v ".git" | xargs -I {} touch {}/

The first part of that find . -type d prints out a simple list of every directory inside the current one. That’s a great place to start. Then we do grep -v ".git" to remove any git-related directories.

The xargs part was the trickiest. I wanted to issue a touch command to create an empty file inside each of the non-git directories. xargs allows you to create a placeholder with the -I flag, which will be substituted with the arguments that get piped in. In this case I’m using the string "{}" as the placeholder.

Now, I can execute touch {}/ and xargs will issue that command for every directory returned by find and filtered by grep, replacing the {} with the directory path in front of the filename.

Leave a Reply

Your email address will not be published.