当前位置:首页 > 操作系统 > Linux

Linux shell 字符串常用操作

  1. 取变量的长度

[root@oldjun-study scripts]# var=oldboy123
[root@oldjun-study scripts]# echo ${var}
oldboy123
[root@oldjun-study scripts]# echo ${#var}
9

#例如:
#以下判断用read输入一个值,如果长度为0,则值为空,否则打印出变量的值
[root@oldjun-study scripts]# cat if4.sh 
#!/bin/bash
read -p "pls input a num: " a

if [ ${#a} -eq 0 ]
then 
    echo "a is null,pls input a nums again!"
    exit 1
else
    echo "a=$a"
fi

#测试
[root@oldjun-study scripts]# sh if4.sh 
pls input a num: 
a is null,pls input a nums again!
[root@oldjun-study scripts]# sh if4.sh 
pls input a num: d
a=d
[root@oldjun-study scripts]# sh if4.sh 
pls input a num: 123
a=123

2. 文件名和目录的截取

[root@oldjun-study scripts]# test="/etc/sysconfig/network-scripts/ifcfg-eth0"
[root@oldjun-study scripts]# echo ${test}
/etc/sysconfig/network-scripts/ifcfg-eth0

#取文件名
[root@oldjun-study scripts]# echo ${test##*/}
ifcfg-eth0

#取目录
[root@oldjun-study scripts]# echo ${test%/*} 
/etc/sysconfig/network-scripts

#使用命令basename 和dirname也可以达到同样的效果
[root@oldjun-study scripts]# echo `basename $test`
ifcfg-eth0
[root@oldjun-study scripts]# echo `dir $test`     
/etc/sysconfig/network-scripts/ifcfg-eth0

原文:http://l19891223j.blog.51cto.com/888280/1688392


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐