7

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?

4

2 回答 2

27

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 --> 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
于 2013-07-30T14:09:00.407 回答
2

If your directory naming structure is numbered like your example IRL you could do the following:

touch ~/main/submain{1..N}/file.txt

This would put file.txt in every folder named submain1 through to submainN

If they're not numbered 1-N you could also try:

touch ~/main/{foldername,differentfolder,anotherfolder}/file.txt

This is a less general solution than the above but may be more understandable for learners!

于 2021-08-26T12:40:21.443 回答