一、打印字符串长度
如下,循环打印下面这名话字母数不大于6个的单词
She could see the open door of a departmental office.
vim print-str.sh
#!/bin/bash
#打印字符串个数
#第一种解决思路
for i in She could see the open door of a departmental office
do
[ ${#i} -le 6 ]&& echo $i
done
echo +++++++++++++++++++++++++++++++++++++
#第二种解决思路
for i in She could see the open door of a departmental office
do
[ `echo $i|wc -L` -le 6 ]&& echo $i
done
echo +++++++++++++++++++++++++++++++++++++
#第三种解决思路
echo "She could see the open door of a departmental office" |awk ‘{for(i=1;i<=NF;i++) if(length($i)<=6) print $i}‘
上面脚本中有一个点给大家说一下:
${#}的作用
帮助文档说明如下:
${#parameter}
${#var} 可以用来计算出变量值的长度
[root@xuegod72 ~]# NAME=martin
[root@xuegod72 ~]# echo ${#NAME}
6
那么${ }还有一些其它方面的作用,比如截取、替换
比如我们定义一个变量:file=/var/log/message
${file#*/}: 删掉第一个 / 及其左边的字符串
[root@xuegod72 ~]# echo ${file#*/}
var/log/message
${file##*/}: 删掉最后一个 / 及其左边的字符串
[root@xuegod72 ~]# echo ${file##*/}
message
${file#*.}: 删掉第一个 . 及其左边的字符串
[root@xuegod72 ~]# file=/var/log/yum.log/xuegod.txt
[root@xuegod72 ~]# echo ${file#*.}
log/xuegod.txt
${file##*.}: 删掉最后一个 . 及其左边的字符串:
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file##*.}
txt
${file%/*}: 删掉最后一个 / 及其右边的字符串:
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file%/*}
/var/log/yum.log
${file%%/*}: 删掉第一个 / 及其右边的字符串:
[root@xuegod72 ~]# echo ${file%%/*}
空值
${file%.*}: 删掉最后一个 . 及其右边的字符串
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file%.*}
/var/log/yum.log/xuegod
${file%%.*}: 删掉第一个 . 及其右边的字符串
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file%%.*}
/var/log/yum
说明:
# 是去掉左边(键盘上#在 $ 的左边)
% 是去掉右边(键盘上% 在$ 的右边)
单一符号是最小匹配;两个符号是最大匹配
字符串截取
字符串提取:
${file:0:5}:提取最左边的 5 个字节(中间用冒号分开)
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file:0:5}
/var/
${file:5:5}:提取第 5 个字节右边的连续5个字节
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file:5:5}
log/y
对变量值进行替换
${file/var/opt}:将第一个var 替换为opt
[root@xuegod72 ~]# file=/var/log/yum.log/martin.txt
[root@xuegod72 ~]# echo ${file/var/opt}
/opt/log/yum.log/xuegod.txt
${file/var/opt}:将全部var 替换为opt
[root@xuegod72 ~]# file=/var/log/var.log/var.txt
[root@xuegod72 ~]# echo ${file//var/opt}
/opt/log/opt.log/opt.txt
本文出自 “Linux_System” 博客,请务必保留此出处http://4402071.blog.51cto.com/4392071/1910024
原文地址:http://4402071.blog.51cto.com/4392071/1910024