在小節中,我們將學習如何計算給定字串的子字串。
子字串是字串中的字元序列。Bash提供了一個從字串提取資訊的選項,Bash中可以使用多種方法提取數字或給定的字串。
例如,"welcome you visits zaixian."
是"Welcome you visits xuhuhu.com"
的子字串。
語法
提取子字串的命令是內置的bash命令,因此從性能角度來看非常有用。子字串提取的語法可以定義為:
${variable:offset:length}
其中,
variable
是包含字串的變數名稱。offset
用於指定從何處開始提取字串的位置。length
用於指定從偏移量開始執行的字元範圍。
注意:分配長度是可選的。如果未提供
length
,則子字串的結尾將是字串的結尾。
下麵通過一些示例從字串中提取子字串的概念。
示例1:從開始提取直到特定字元
#!/bin/bash
#Script to extract first 10 characters of a string
echo "String: We welcome you on zaixian."
str="We welcome you on zaixian."
echo "Total characters in a String: ${#str} "
substr="${str:0:10}"
echo "Substring: $substr"
echo "Total characters in Substring: ${#substr} "
執行上面示例代碼,得到以下結果:
示例2:從特定字元開始提取
#!/bin/bash
#Script to print from 11th character onwards
str="We welcome you on zaixian."
substr="${str:11}"
echo "$substr"
在這裏,子字串的結尾與字串的結尾相同。
執行上面示例代碼,得到以下結果:
maxsu@zaixian:~/bashcode$ vi substring.sh
maxsu@zaixian:~/bashcode$ ./substring.sh
you on zaixian.
示例3:提取單個字元
#!/bin/bash
#Script to print 11th character of a String
str="We welcome you on zaixian."
substr="${str:11:1}"
echo "$substr"
執行上面示例代碼,得到以下結果:
maxsu@zaixian:~/bashcode$ cat /dev/null > substring.sh
maxsu@zaixian:~/bashcode$ vi substring.sh
maxsu@zaixian:~/bashcode$ ./substring.sh
y
示例4:從末尾提取特定字元
#!/bin/bash
#Script to extract 11 characters from last
str="We welcome you on zaixian."
substr="${str:(-11)}"
echo "$substr"
執行上面示例代碼,得到以下結果:
maxsu@zaixian:~/bashcode$ cat /dev/null > substring.sh
maxsu@zaixian:~/bashcode$ vi substring.sh
maxsu@zaixian:~/bashcode$ ./substring.sh
on zaixian.