在 bash 中使用 {} 範圍表達式

在編寫 shell 腳本時,有時需要生成數字或字符串序列。這種序列數據的一種常見用途是用於循環迭代。

雖然可以使用 seq 之類的專用工具來生成一系列數字,但 bash 本身提供大括號擴展,實際上沒有必要在 bash 腳本中添加此類外部依賴項。在本教程中,讓我們瞭解如何使用大括號擴展在 shell 腳本中生成數據序列和一些有用的大括號擴展示例。

{} 花括號使用說明

Bash 內置的 range 函數是通過所謂的{}大括號擴展實現的。簡而言之,大括號擴展允許根據提供的字符串和數字數據生成字符串序列。大括號擴展的語法如下。

{<string1>,<string2>,...,<stringN>}
{<start-number>..<end-number>}
{<start-number>..<end-number>..<increment>}
<prefix-string>{......}
{......}<suffix-string>
<prefix-string>{......}<suffix-string>

實例一:列出字符串序列

大括號擴展的第一個用例是一個簡單的字符串列表,它是大括號內以逗號分隔的字符串列表。這裏是簡單地列出預定義的字符串數據。

下面使用 for 循環,列出大括號中的字符串,如下所示。

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

要定義 10 到 20 之間的整數序列:

[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

如果要生成 0 到 20 之間增量爲 2 的數字序列:

[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 腳本有用,而且在命令行環境中也很有用。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Bsa2xgxtY6KDsqCIH5g6iA