个性化阅读
专注于IT技术分析

bash查找字符串find

点击下载

本文概述

在本主题中,我们演示了如何在Bash Scripting中查找字符串的长度。

任何字符串中的字符总数表示字符串的长度。在某些情况下,我们可能需要了解字符串的长度才能执行某些特定任务。大多数编程语言都有自己的内置函数来计算字符数。但是,Bash不包含此类内置函数。但是,在Bash脚本中,可以使用几种方法来查找字符串的长度。

bash字符串长度

要计算字符串的长度,我们可以使用以下任何语法:

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

注意:请注意在$ string周围使用双引号。如果字符串中包含空格,则双引号非常重要。否则,可以忽略它。为了安全起见,我们建议始终在$ string周围使用双引号。

上面的语法定义了我们可以使用bash命令或不使用bash命令来查找字符串的长度。使用“

在Bash中查找字符串长度的示例

下面提供了一些示例,这些示例说明了在bash shell脚本中查找字符串长度的不同方法:

例子1

计算字符串长度的最简单方法是使用’

Bash脚本

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

str="Welcome to srcmini"
length=${#str}

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

输出量

Length of 'Welcome to srcmini' is 21

例子2

另一种计算字符串长度的方法是将`expr`命令与’length’关键字一起使用。在这个例子中,我们使用了`expr length“ $ str”`来查找字符串的长度。

Bash脚本

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

str="Welcome to srcmini"
length=`expr length "$str"`

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

输出量

Length of 'Welcome to srcmini' is 21

例子3

在这个例子中,我们使用了`expr“ $ str”:’。*’`查找字符串的长度。在这里,str是一个字符串变量。

Bash脚本

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

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

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

输出量

Length of 'Welcome to srcmini' is 21

例子4

在这个例子中,我们使用了`wc`命令来查找字符串的长度。

Bash脚本

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

str="Welcome to srcmini"
length=`echo $str | wc -c`

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

输出量

Length of 'Welcome to srcmini' is 22

例子5

在这个例子中,我们使用了“ awk”命令来查找字符串的长度。

Bash脚本

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

str="Welcome to srcmini"
length=`echo $str |awk '{print length}'`

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

输出量

Length of 'Welcome to srcmini' is 21

结论

在本主题中,我们通过示例了解了用于查找字符串长度的语法。


赞(0)
未经允许不得转载:srcmini » bash查找字符串find

评论 抢沙发

评论前必须登录!