linux - 如何在 bash 的每个子目录中创建相同的目录?

标签 linux bash shell ubuntu

我一直在尝试在“example”的所有子目录中创建目录“a”。

我尝试过以下内容:

mkdir example/*/a

但它不使用 '*' 作为通配符,返回 mkdir: can not create «example/*/a» directory: It does not Existence file or directory

请注意,示例中的子目录太多,因此无法通过创建列表来完成。

我不想用for循环来做到这一点,因为我正在学习bash并且不允许我使用循环。也许,没有办法避免 for 循环,在这种情况下,请告诉我:)。

谢谢。

最佳答案

尝试:

dirs=( example/*/ )
mkdir -v "${dirs[@]/%/a}"
  • dirs=( example/*/) 创建 example 的所有子目录的数组 ( (example/dir1/example/dir2/... ) )。
  • "${dirs[@]/%/a}" 扩展为包含 dirs 的所有元素且带有 a 的列表附加到每个文件 ( (example/dir1/a example/dir2/a ...) )。

如果您有非常大量子目录,上述代码中的mkdir可能会失败,并出现“参数列表太长”错误。请参阅Argument list too long error for rm, cp, mv commands .

避免该问题的一种方法是将要创建的以 NUL 结尾的目录列表传递给 xargs -0:

dirs=( example/*/ )
printf '%s\0' "${dirs[@]/%/a}" | xargs -0 mkdir -v

如果需要,这将运行多个 mkdir 命令,每个命令都有一个不超过限制的参数列表。

但是,如果目录数量那么很大,您可能会遇到性能问题,因为 Bash (不必要但不可避免)对 example/*/生成的列表进行排序)。在这种情况下,最好使用find。一种方法是:

find example -maxdepth 1 -mindepth 1 -type d -printf '%p/a\0' | xargs -0 mkdir -v

find 内置了对 xargs 类似 -exec ... + 行为的支持。然而,在这种情况下使用起来有点麻烦。我能很快想到的最好的办法是:

find example -maxdepth 1 -mindepth 1 -type d    \
    -exec bash -c 'mkdir -v "${@/%//a}"' bash {} +

因为它在运行 mkdir 之前将 /a 添加到由 find 传递给 bash 的所有参数中无论如何,它可能会遇到“参数列表太长”错误。我将其留在这里,因为它说明了一种有时有用的技术,但我建议不要使用它。

关于linux - 如何在 bash 的每个子目录中创建相同的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71307816/

相关文章:

c++ - 从 vim 编译 C++ 代码

linux - 是否可以根据条件语句加载列表 perl 模块?

混帐上传包 : command not found

linux - sed 正则表达式不贪心?

bash - Windows 上的 GCC - Windows 上 Ubuntu 上的 Bash (WSL)、CygWin、MinGW

shell - 获取 Spacemacs/Emacs GUI 版本以识别 nix-shell 环境

shell - 用 shell(ubuntu) 查找单词并复制以下单词?

php.ini upload_max_filesize 未更新

linux - 这个程序集如何不崩溃?

linux - 如何将多个键盘输入与 linux 命令一起传递