Bash查詢字串


在本小節中,將演示如何在Bash指令碼中計算字串的長度。

字串中的字元總數表示字串的長度。在某些情況下,我們可能需要了解字串的長度才能執行某些特定任務。大多數程式設計語言都有自己的內建函式來計算字元數。但是,Bash沒有此類內建函式。在Bash指令碼中,可以使用幾種方法來查詢字串的長度。

1. Bash計算字串的長度

要計算字串的長度,可以使用以下幾種語法之一:

1.  ${#string}  
2.  expr length "$string"  
3.  expr "$string" :'.*'  
4.  $str | wc -c  
5.  $str |awk '{print length}'

注意:請注意在$string周圍使用雙引號。如果字串中包含空格,則雙引號非常重要。否則,可以忽略它。為了安全起見,建議始終在$string周圍使用雙引號。

上面的語法定義了可以使用或不使用bash命令來查詢字串的長度。使用#號,可以計算字串的長度,而無需應用任何bash命令。下面通過一些範例來更清楚地理解:

2. Bash查詢字串長度的範例

下面提供了一些範例,這些範例說明了在bash shell指令碼中查詢字串長度的不同方法:

範例1

計算字串長度的最簡單方法是使用#符號。在此範例中,使用$[#string_variable_name}查詢字串的長度。

Bash指令碼範例

#!/bin/bash  
#Bash program to find the length of a string  

str="Welcome to Tw511.com"  
length=${#str}  

echo "Length of '$str' is $length"

執行上面範例程式碼,得到以下結果:

範例2

計算字串長度的另一種方法是將expr命令與length關鍵字一起使用。在這個例子中,使用了expr length "$str"來計算字串的長度。

Bash指令碼範例

#!/bin/bash  
#Bash script to find the length of a string  

str="Welcome to Tw511.com"  
length=`expr length "$str"`  

echo "Length of '$str' is $length"

執行上面範例程式碼,得到以下結果:

Length of 'Welcome to Tw511.com' is 21

範例3

在這個例子中,我們使用了expr "$str": ' .*'來計算字串的長度。在這裡,str是一個字串變數。

Bash指令碼範例

#!/bin/bash  
#Bash script to find the length of a string  

str="Welcome to Tw511.com"  
length=`expr "$str" : '.*'`  

echo "Length of '$str' is $length"

執行上面範例程式碼,得到以下結果:

Length of 'Welcome to Tw511.com' is 21

範例4

在這個例子中,我們使用了wc命令來查詢字串的長度。

Bash指令碼範例

#!/bin/bash  
#Bash script to find the length of a string  

str="Welcome to Tw511.com"  
length=`echo $str | wc -c`  

echo "Length of '$str' is $length"

執行上面範例程式碼,得到以下結果:

Length of 'Welcome to Tw511.com' is 21

範例5

在這個例子中,我們使用了awk命令來查詢字串的長度。

Bash指令碼範例

#!/bin/bash  
#Bash script to find the length of a string  

str="Welcome to xntutor.com"  
length=`echo $str |awk '{print length}'`  

echo "Length of '$str' is $length"

執行上面範例程式碼,得到以下結果:

Length of 'Welcome to xntutor.com' is 22