在 Bash 中提取子字串
Fumbani Banda
2023年1月30日
Bash
Bash String
本教程演示了使用 cut 命令、子字串擴充套件和內部欄位分隔符 (IFS) 在 bash 中提取子字串的不同方法。
在 Bash 中使用 cut 命令提取子字串
下面的指令碼使用 cut 命令來提取子字串。-d 選項指定用於將字串劃分為欄位的分隔符,而 -f 選項設定要提取的欄位的編號。
在我們的例子中,字串使用 _ 作為分隔符進行分割,為了訪問第三個欄位,我們將引數 3 傳遞給 -f 選項。
#!/bin/bash
printf "Script to extract a substring!\n\n"
numbers='one_two_three_four_five'
printf "full string: $numbers\n"
substring=$(echo $numbers | cut -d '_' -f 3)
printf "substring: $substring\n"
執行 bash 指令碼如下。
bash substring.sh
從輸出中,從字串 one_two_three_four_five 中提取了子字串 three。
Script to extract a substring!
full string: one_two_three_four_five
substring: three
在 Bash 中使用子字串擴充套件提取子字串
子字串擴充套件是一個內建的 bash 功能。它使用以下語法。
$(variable:offset:length)
variable 是包含字串的變數名稱。offset 用於指定開始提取字串的位置。length 用於指定要提取的字元範圍,不包括 offset。
下面的指令碼將變數名稱設定為 numbers,將 offset 設定為 4,將要提取的字串的 length 設定為 3。
#!/bin/bash
printf "Script to extract a substring!\n\n"
numbers='one_two_three_four_five'
substring=${numbers:4:3}
printf "full string: $numbers\n"
printf "substring: $substring\n"
執行 bash 指令碼如下。
bash substring.sh
從輸出中,從字串 one_two_three_four_five 中提取了子字串 two。
Script to extract a substring!
full string: one_two_three_four_five
substring: two
在 Bash 中使用 IFS 提取子字串
IFS 代表內部欄位分隔符。IFS 用於擴充套件後的單詞拆分,並使用內建的讀取命令將行拆分為單詞。
在下面的指令碼中,IFS 已設定為 _。這意味著它應該使用 _ 作為分隔符拆分變數 numbers 中的字串。一旦字串被拆分,我們就可以使用語法 $[integer] 訪問單詞。第一個單詞可以通過 $1 訪問,第二個單詞可以通過 $2 訪問,第三個單詞可以通過 $3 訪問,依此類推。
#!/bin/bash
printf "Script to extract a substring!\n\n"
numbers='one_two_three_four_five'
IFS="_"
set $numbers
printf "full string: $numbers\n"
printf "substring: $2\n"
執行 bash 指令碼如下。
bash substring.sh
從輸出中,從字串 one_two_three_four_five 中提取了子字串 two。
Script to extract a substring!
full string: one_two_three_four_five
substring: two
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Fumbani Banda
