博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Bash/KSH/SH Shell: Find The Length Of a String On a UNIX, Linux, BSD, and OS X
阅读量:4285 次
发布时间:2019-05-27

本文共 1281 字,大约阅读时间需要 4 分钟。

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

转载地址:http://bhsgi.baihongyu.com/

你可能感兴趣的文章
python中enumerate函数实战
查看>>
python中使用shuffle和permutation对列表进行随机洗牌区别
查看>>
使用js连接mqtt
查看>>
ubuntu下mysql数据库docker的定时备份脚本
查看>>
python3基于 Doc2Vec 的电影评论分析实战
查看>>
Centos 7 下influxdb docker的安装及使用
查看>>
python中lambda表达式使用实战
查看>>
centos 7中firewalld防火墙命令的使用
查看>>
python实现协程的三种方式
查看>>
WARNING: IPV4 forwarding is disabled. Networking will not work. 运行centos docker的时候报错
查看>>
在centos docker中封装flask应用,并使用命令和dockerfile两种方式制作镜像实战
查看>>
GARCH(二)
查看>>
Android中自带的list布局
查看>>
Adapter之大数据滑动效率优化和分页加载数据
查看>>
SQL读取大量数据的字符
查看>>
Android界面View及ViewGroup
查看>>
使用java实现高中数学中自由组合
查看>>
Java中密码加密之PBE算法
查看>>
0基础配置Android Studio
查看>>
Exception in thread "http-bio-8080-exec-7"内存溢出问题
查看>>