seq
之类的专用工具来生成一系列数字,但 bash 本身提供大括号扩展,实际上没有必要在 bash 脚本中添加此类外部依赖项。在本教程中,让我们了解如何使用大括号扩展在 shell 脚本中生成数据序列和一些有用的大括号扩展示例。{}花括号使用说明
{}
大括号扩展实现的。简而言之,大括号扩展允许根据提供的字符串和数字数据生成字符串序列。大括号扩展的语法如下。{<string1>,<string2>,...,<stringN>}
{<start-number>..<end-number>}
{<start-number>..<end-number>..<increment>}
<prefix-string>{......}
{......}<suffix-string>
<prefix-string>{......}<suffix-string>
实例一:列出字符串序列
[root@localhost ~]# for fruit in {apple,orange,lemon}; do echo $fruit ; done
apple
orange
lemon
[root@localhost ~]# mkdir -p /tmp/users/{dan,john,alex,michael,emma}
[root@localhost ~]# ls -l /tmp/users/
total 0
drwxr-xr-x 2 root root 6 Aug 6 16:23 alex
drwxr-xr-x 2 root root 6 Aug 6 16:23 dan
drwxr-xr-x 2 root root 6 Aug 6 16:23 emma
drwxr-xr-x 2 root root 6 Aug 6 16:23 john
drwxr-xr-x 2 root root 6 Aug 6 16:23 michael
[root@localhost ~]# touch /tmp/file{1,2,3,4}.log
[root@localhost ~]# ll /tmp/
total 0
-rw-r--r-- 1 root root 0 Aug 6 16:24 file1.log
-rw-r--r-- 1 root root 0 Aug 6 16:24 file2.log
-rw-r--r-- 1 root root 0 Aug 6 16:24 file3.log
-rw-r--r-- 1 root root 0 Aug 6 16:24 file4.log
实例二:定义一个数字范围
{<start-number>..<end-number>}
{<start-number>..<end-number>..<increment>}
[root@localhost ~]# echo {10..20}
10 11 12 13 14 15 16 17 18 19 20
[root@localhost ~]# for num in {10..20}; do echo $num ;done
10
11
12
13
14
15
16
17
18
19
20
[root@localhost ~]# echo {0..20..2}
0 2 4 6 8 10 12 14 16 18 20
[root@localhost ~]# echo {20..10}
20 19 18 17 16 15 14 13 12 11 10
[root@localhost ~]# echo {20..10..-2}
20 18 16 14 12 10
[root@localhost ~]# for num in {00..20..2}; do echo $num ; done
00
02
04
06
08
10
12
14
16
18
20
实例三:生成字母序列
[root@localhost ~]# cat brace.sh
#!/bin/bash
for char1 in {A..B}; do
for char2 in {A..B}; do
echo "${char1}${char2}"
done
done
实例四:生成带有前缀、后缀的字符串序列
[root@localhost ~]# for file in img_{00..05}.jpg; do echo $file ; done
img_00.jpg
img_01.jpg
img_02.jpg
img_03.jpg
img_04.jpg
img_05.jpg
实例五:多个{}花括号组合使用
for char1 in {A..Z}; do
for char2 in {A..Z}; do
echo "${char1}${char2}"
done
done
for str in {A..Z}{A..Z}; do
echo $str
done
总 结
{}
允许您在单个命令行中轻松生成一系列任意字符串。大括号扩展不仅对 shell 脚本有用,而且在命令行环境中也很有用。END
官方站点:www.linuxprobe.com
Linux命令大全:www.linuxcool.com
刘遄老师QQ:5604241
Linux技术交流群:3586725
(新群,火热加群中……)
想要学习Linux系统的读者可以点击"阅读原文"按钮来了解书籍《Linux就该这么学》,同时也非常适合专业的运维人员阅读,成为辅助您工作的高价值工具书!