10

How do I recursively add(or touch) a file into the current directory, as well as all sub-directories?

For example,
I would like to turn this directory tree:

.
├── 1
│   ├── A
│   └── B
├── 2
│   └── A
└── 3
    ├── A
    └── B
        └── I   
9 directories, 0 files

into

.
├── 1
│   ├── A
│   │   └── file
│   ├── B
│   │   └── file
│   └── file
├── 2
│   ├── A
│   │   └── file
│   └── file
├── 3
│   ├── A
│   │   └── file
│   ├── B
│   │   ├── file
│   │   └── I
│   │       └── file
│   └── file
└── file

9 directories, 10 files
14

How about:

find . -type d -exec cp file {} \;

From man find:

   -type c
          File is of type c:
           d      directory

   -exec command ;
          Execute  command;  All following arguments to find are taken 
          to be arguments to the command until an  argument  consisting 
          of `;' is encountered.  The string `{}' is replaced by the 
          current file

So, the command above will find all directories and run cp file DIR_NAME/ on each of them.

  • or, find . -type d -exec touch file {} \; – ChuckCottrill Oct 9 '13 at 5:19
  • 1
    or, find . -type d -exec touch {}/file\; – Ned64 Sep 8 '15 at 12:24
5

If you just want to create an empty file, you can use touch and a shell glob. In zsh:

touch **/*(/e:REPLY+=/file:)

In bash:

shopt -s globstar
for d in **/*/; do touch -- "$d/file"; done

Portably, you can use find:

find . -type d -exec sh -c 'for d; do touch "$d/file"; done' _ {} +

Some find implementations, but not all, let you write find . -type d -exec touch {}/file \;

If you want to copy some reference content, then you'll have to call find in a loop. In zsh:

for d in **/*(/); do cp -p reference_file "$d/file"; done

In bash:

shopt -s globstar
for d in **/*/; do cp -p reference_file "$d/file"; done

Portably:

find . -type d -exec sh -c 'for d; do cp -p reference_file "$d/file"; done' _ {} +
2

When wanting to touch files called $name in the current directory and in all subdirectories, this will work:

find . -type d -exec touch {}/"${name}"  \;

Note that the comment by ChuckCottrill to the answer by terdon does NOT work, as it will only touch the file called $name in the current directory and the directory itself.

It will not create files in subdirectories as requested by the OP, while this version here will.

0

To actually just create a file, you can use touch with find:

$ find . -type d -exec touch {}/file \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.