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
How to create a file in multiple directories in Linux?
提问by rage
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.
我只是在 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 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?
我怎样才能让创建的文件touch
存在于所有submain
目录中?我的第一个想法是有一个循环来访问每个目录,cd
并touch
在每次迭代时调用该命令。我想知道是否有更优雅的解决方案?
回答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 withtouch {}/hiya
what we do is to touch that "something"/hiya. The final\;
is required byexec
infind
clauses.
find . -type d
--> 在目录结构中搜索目录。-exec touch {}/hiya \;
--> 给定每个结果,其值存储在{}
. 所以touch {}/hiya
我们所做的就是触摸那个“东西”/hiya。in子句\;
要求final 。exec
find
Another example of find
usage:
另一个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