Bash/KSH/SH Shell: Find The Length Of a String On a UNIX, Linux, BSD, and OS X

While writing a shell script you may want to find out the length of a string. While reading GNU expr command man page I found an interesting option as follows:

expr length STRING

For example display the length of "nixcraft" word/string, enter:

 
expr length "nixcraft"
 

OR set it as follows:

 
var="nixcraft"
expr "${var}" : '.*'
 

Sample outputs:

8

Finding length of string in bash

The syntax is as follows:

var="nixCraft"
l=${#var} 
echo "Length of string \"${var}\" is ${l}."

Sample outputs:

Length of string "nixCraft" is 8.

String length in ksh or older unix oses

You can use the wc command as follows:

## pass the -c option to wc to get the number of bytes in $domain variable ##
domain='www.cyberciti.biz'
echo -n "$domain" | wc -c

Sample outputs:

17

expr and POSIX

Please note that the expr command is not concerned with POSIX (open system standards based on Unix). You can try old good KSH/SH/Bash command as follows which should work with any UNIX-likeo operating systems such as FreeBSD, OpenBSD, Solaris, IBM AIX, HP-UX and more:

 
myVar="nixcraft"
echo "${#myVar}"
 

Sample outputs:

8

Another option is to use Perl or Python:

 
echo "What you seek is seeking you" | perl -nle ' print length '
 

Sample outputs:

28

Few more examples:

% echo nixcraft | awk ' { print length } '
8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值