[bash] 借助花括号扩展来批量生成内容

背景

bash 支持花括号扩展,举个例子,使用以下命令可以输出所有的 1 位 16 进制数。

bash 复制代码
echo 0x{0..9} 0x{A..F}

正文

Brace Expansion 一文中介绍了 bash 中的花括号扩展。

Brace Expansion 中提到了如下内容

基本形式

Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript.

从这部分描述中,我们知道花括号扩展有两种基本形式

  • [preamble] + {a,b,c} + [postscript]
  • [preamble] + {x..y[..incr]} + [postscript]

第一种形式的例子

bash 复制代码
echo {red,green,blue}.txt

第二种形式的例子

bash 复制代码
echo {2020..2026}
echo {1..9..2}
echo {a..g}

嵌套形式

Brace Expansion 中提到了如下内容

Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved.

例子

生成所有3位2进制数
bash 复制代码
echo 0b{0,1}{0,1}{0,1}
创建大量文件
bash 复制代码
# 下方的命令会尝试创建 temp 目录并在其中创建 26 * 10 = 260 个文件
mkdir temp && cd temp && touch file-{a..z}{1..10}.txt
创建大量目录
bash 复制代码
# 以下命令会尝试创建 2020,2021,2022,2023,2024,2025,2026 这些目录,
# 并且会尝试在这些目录下创建 01,02,03,04,05,06,07,08,09,10,11,12 子目录
mkdir -p {2020..2026}/{01..12}

参考资料

相关推荐
吴声子夜歌7 天前
Shell编程实例——编写安全的shell脚本(二)
linux·运维·shell
吴声子夜歌9 天前
Shell编程实例——内务及管理任务(一)
linux·运维·shell
吴声子夜歌9 天前
Shell编程实例——高级脚本编程(一)
linux·运维·网络·shell
吴声子夜歌9 天前
Shell编程实例——bash的配置与自定义(二)
linux·运维·shell
吴声子夜歌10 天前
Shell编程实例——与解析相关的任务(二)
linux·运维·shell
吴声子夜歌10 天前
Shell编程实例——脚本编程的附加特性
linux·运维·shell
云计算练习生10 天前
什么是内核?操作系统内核到底管哪些事
linux·windows·操作系统·内核·shell
吴声子夜歌13 天前
Shell编程实例——bash入门
linux·运维·shell
Swizard13 天前
Linux 日志神器 journalctl 完全指南:彻底替代传统日志查看方式
shell
吴声子夜歌14 天前
Shell编程——数组
linux·运维·shell