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 xuhuhu.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 xuhuhu.com"
length=`expr length "$str"`

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

執行上面示例代碼,得到以下結果:

Length of 'Welcome to xuhuhu.com' is 21

示例3

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

Bash腳本示例

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

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

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

執行上面示例代碼,得到以下結果:

Length of 'Welcome to xuhuhu.com' is 21

示例4

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

Bash腳本示例

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

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

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

執行上面示例代碼,得到以下結果:

Length of 'Welcome to xuhuhu.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

上一篇: Bash字串 下一篇: Bash拆分字串