简体   繁体   中英

How to create a file in multiple directories in Linux?

I'm just doing this as an exercise in Linux but, I was wondering how could i use touch to create one empty file and have it exist in multiple directories.

For example i have a directory layout like the followng:

~/main
~/main/submain1
~/main/submain2
.
.
.
~/main/submainN

How could i get the file created by touch to exist in all of the submain directories? My first thought is to have a loop that visits each directory using cd and call the touch command at every iteration. I was wondering if there was a more elegant solution?

What about this:

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

this will work for any depth level of directories.

Explanation

find . -type d -exec touch {}/hiya \;
  • find . -type d find . -type d --> searchs directories in the directory structure.
  • -exec touch {}/hiya \\; --> given each result, its value is stored in {} . So with touch {}/hiya what we do is to touch that "something"/hiya. The final \\; is required by exec in find clauses.

Another example of find usage:

find . -type d -exec ls {} \;

Test

$ mkdir a1
$ mkdir a2
$ mkdir a3
$ mkdir a1/a3

Check dirs:

$ find . -type d
.
./a2
./a1
./a1/a3
./a3

Touch files

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

Look for them:

$ find . -type f
./a2/hiya
./hiya
./a1/hiya
./a1/a3/hiya
./a3/hiya

And the total list of files/dirs is:

$ find .
.
./a2
./a2/hiya
./hiya
./a1
./a1/hiya
./a1/a3
./a1/a3/hiya
./a3
./a3/hiya

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM