[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}

参考资料

相关推荐
钱栈up1 天前
耳机音效不对,我顺手查了系统更新,结果挖出个崩溃了整天的服务
windows·shell
qetfw1 天前
grep 文本筛选:匹配、反选与退出状态验证
linux·shell
xbzb8 天前
Shell 函数:语法、传参与递归调用一次讲透
shell·递归·函数·调用·传参·递归调用
东鹏特饮10 天前
15个实用Linux运维脚本
linux·运维·shell·脚本·redhat·常用生产脚本
Zoom10 天前
【开源】7 天,我用 Rust 复刻了 FinalShell!Rhost v1.0.0 发布
rust·electron·shell
Lsetea19 天前
OpenSSL s_client退出码为0却证书验证失败:严格校验与Shell管道排查
https·shell·ssl证书·openssl·tls
fox_charon20 天前
Windows 下 CLI 参数的引号陷阱:为什么 --resume 'uuid' 会失败
windows·shell·cmd·cli·引号
吴声子夜歌1 个月前
Shell编程实例——编写安全的shell脚本(二)
linux·运维·shell
吴声子夜歌1 个月前
Shell编程实例——内务及管理任务(一)
linux·运维·shell
吴声子夜歌1 个月前
Shell编程实例——高级脚本编程(一)
linux·运维·网络·shell