bash 如何在Linux中的多个目录中创建文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17949316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:03:50  来源:igfitidea点击:

How to create a file in multiple directories in Linux?

linuxbash

提问by rage

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

我只是在 Linux 中做这个练习,但是,我想知道如何touch创建一个空文件并将其存在于多个目录中。

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 touchto exist in all of the submaindirectories? My first thought is to have a loop that visits each directory using cdand call the touchcommand at every iteration. I was wondering if there was a more elegant solution?

我怎样才能让创建的文件touch存在于所有submain目录中?我的第一个想法是有一个循环来访问每个目录,cdtouch在每次迭代时调用该命令。我想知道是否有更优雅的解决方案?

回答by fedorqui 'SO stop harming'

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 {}/hiyawhat we do is to touch that "something"/hiya. The final \;is required by execin findclauses.
  • find . -type d--> 在目录结构中搜索目录。
  • -exec touch {}/hiya \;--> 给定每个结果,其值存储在{}. 所以touch {}/hiya我们所做的就是触摸那个“东西”/hiya。in子句\;要求final 。execfind

Another example of findusage:

另一个find用法示例:

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