繁体   English   中英

Linux shell:LOOP用于在每个文件夹中创建文件

[英]Linux shell: LOOP for create file in each folder

专家

我想在每个文件夹中创建文件。 这是我的命令

for i in `ls`;do cd $i;touch test.txt;done

-bash: cd: 10/: No such file or directory
-bash: cd: 2/: No such file or directory
-bash: cd: 3/: No such file or directory
-bash: cd: 4/: No such file or directory
-bash: cd: 5/: No such file or directory
-bash: cd: 6/: No such file or directory
-bash: cd: 7/: No such file or directory
-bash: cd: 8/: No such file or directory
-bash: cd: 9/: No such file or directory

它只在文件夹1/生成test.txt ,其余文件夹为空。 我认为原因是我的命令缺乏{ }来澄清LOOP的规模。

你能帮我更新一下我的命令吗?

for dir in */; do
   touch "$dir/test.txt"
done
  1. 无需cd进入目录即可在其中创建文件。
  2. 不要解析ls的输出。 ls的输出仅供查看。 如果您的文件或目录包含包含文字换行符或空格的名称,则解析它将会中断。
  3. 模式*/将匹配当前目录中的任何目录。
  4. 引用你的变量扩展。 如果IFS设置为数字,您的代码将会中断。

如果你真的需要在目录中执行cd ,请在子shell中执行。 更改的工作目录仅影响子shell,无需cd返回。

for dir in */; do
   ( cd "$dir" && touch test.txt )
done

我们假设您当前的工作目录中有以下10个文件夹:

tree .
.
├── 1
├── 10
├── 2
├── 3
├── 4
├── 5
├── 6
├── 7
├── 8
└── 9

您可以运行以下命令来创建文件:

for d in `find . -mindepth 1 -maxdepth 1 -type d`; do touch "$d"/test.txt; done

OUTPUT:

tree .
.
├── 1
│   └── test.txt
├── 10
│   └── test.txt
├── 2
│   └── test.txt
├── 3
│   └── test.txt
├── 4
│   └── test.txt
├── 5
│   └── test.txt
├── 6
│   └── test.txt
├── 7
│   └── test.txt
├── 8
│   └── test.txt
└── 9
    └── test.txt

10 directories, 10 files

说明:

find . -mindepth 1 -maxdepth 1 -type d find . -mindepth 1 -maxdepth 1 -type d将获取当前工作文件夹下正好为1级的所有文件夹,如果省略-mindepth 1那么您将在当前工作目录中创建一个文件. 将被选中,如果省略-maxdepth 1则将在任何深度级别递归创建文件,同时-type d将仅允许对目录进行过滤。

然后,您可以使用循环来创建文件,甚至xargs命令就足够了

cd到一个目录,但你不cd退了出去。 假设列表中的第一个目录为1 ,则您的脚本首先更改为1 ,然后尝试更改为1/10 ,这不存在。

你可以在触摸文件后做一张cd -

更好的是,你完全避免使用cd ,而是touch $i/test.txt

当然,编写的脚本不是很健壮:如果当前目录包含普通文件,它会中断,如果它包含名称中包含空格的条目,它会中断 - 但这是一个不同的问题。

稍微改变你的命令,

for i in `ls -1`;do touch "$i"/test.txt;done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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