Shell脚本之求字符串长度

Shell脚本之求字符串长度

  • 方法1
[root@server4 shells]# echo "afsdfbc" | wc -L
7
  • 方法2
[root@server4 shells]# string='123'     ##定义一个变量string
[root@server4 shells]# echo $string
123
[root@server4 shells]# expr length string
6
[root@server4 shells]# expr length $string
3
  • 方法三:利用awk命令
[root@server4 shells]# str="abcdef"
[root@server4 shells]# echo ${str} | awk '{print length($0)}'
6
  • 方法四:利用wc命令
[root@server4 shells]# str="abcdef"
[root@server4 shells]# echo ${str} | wc -c
7
[root@server4 shells]# man wc
[root@server4 shells]# echo -n ${str} | wc -c
6

注意,这里echo后有没有-n参数是影响结果的,【echo的-n参数表示是否输出输出换行】

你可能感兴趣的:(Linux)