标签:字符串
取字符串切片
1.由第四个字符串开始,截取字符串,至字符串结束
[root@kaibin-test ~]# myname="Hello myworld"
[root@kaibin-test ~]# substr=${myname:3}
[root@kaibin-test ~]# echo $substr
lo myworld2.由第6个字符串开始,截取8个字符长度的字符串
[root@kaibin-test ~]# filename="/root/test.txt"
[root@kaibin-test ~]# substr=${filename:6:8}
[root@kaibin-test ~]# echo $substr
test.txt3.取部分位置变量
#! /bin/bash
echo $0
echo ${@:1} 由第一个位置变量开始,去所有的位置变量
执行结果:
[root@kaibin-test ~]# ./1.sh 66 77 88 99
./1.sh
66 77 88 994.计算字符串长度
[root@kaibin-test ~]# filename="/root/test.txt"
[root@kaibin-test ~]# echo ${#filename}
14变量扩展:对比样式
由字符串前面相比,删除相符者,删除最短的
[root@kaibin-test ~]# filename="/etc/sysconfig/network-scripts/ifcfg-eth0"
[root@kaibin-test ~]# r=${filename#/*/}
[root@kaibin-test ~]# echo $r
sysconfig/network-scripts/ifcfg-eth02.由字符串前面相比,删除相符者,删除最长的
[root@kaibin-test ~]# filename="/etc/sysconfig/network-scripts/ifcfg-eth0"
[root@kaibin-test ~]# r=${filename##/*/}
[root@kaibin-test ~]# echo $r
ifcfg-eth03.由字符串后面相比,删除相符者,删除最短的
[root@kaibin-test ~]# filename="/etc/sysconfig/network-scripts/ifcfg-eth0"
[root@kaibin-test ~]# r=${filename%/*}
[root@kaibin-test ~]# echo $r
/etc/sysconfig/network-scripts4.有字符串后面相比,删除相符者,删除最长的
[root@kaibin-test ~]# url="www.baidu.com"
[root@kaibin-test ~]# r=${url%%.*}
[root@kaibin-test ~]# echo $r
www取代或删除部分字符串
语法:${变量/样式/替换的字符串}
只替换第一个符合的字符串
[root@kaibin-test ~]# act="root:x:0:0:root:/root:/bin/bash"
[root@kaibin-test ~]# r=${act/:/#}
[root@kaibin-test ~]# echo $r
root#x:0:0:root:/root:/bin/bash2.替换所有的符合的字符串
[root@kaibin-test ~]# act="root:x:0:0:root:/root:/bin/bash"
[root@kaibin-test ~]# r=${act//:/#}
[root@kaibin-test ~]# echo $r
root#x#0#0#root#/root#/bin/bash把对比符合的字符串删除
语法:${变量/样式}
只删除第一个符合的字符串
[root@kaibin-test ~]# act="root:x:0:0:root:/root:/bin/bash"
[root@kaibin-test ~]# r=${act/:/}
[root@kaibin-test ~]# echo $r
rootx:0:0:root:/root:/bin/bash2.删除所有符合的字符串
[root@kaibin-test ~]# act="root:x:0:0:root:/root:/bin/bash"
[root@kaibin-test ~]# r=${act//:/}
[root@kaibin-test ~]# echo $r
rootx00root/root/bin/bash取变量名称列表,数组索引列表
取变量名称列表
[root@kaibin-test ~]# filename="ifcfg-eth0"
[root@kaibin-test ~]# dir="/etc/sysconfig/network-scripts/"
[root@kaibin-test ~]# dir_file="$dir/$filename"
[root@kaibin-test ~]# echo ${!di@}
dir dir_file2.取数组索引列表
[root@kaibin-test ~]# ar=(a b c xy z)
[root@kaibin-test ~]# r=${!ar[@]}
[root@kaibin-test ~]# echo $r
0 1 2 3 4
流控制语句
使用复合命令((算数运算))
使用Bash关键词[[]]组成的式子:[[判断式]]
[root@kaibin-test ~]# if [[ str > xyz ]];then > echo "字符串str比较大" > else > echo "字符串str比较小" > fi 字符串str比较小
3.使用内置命令:test判断式
本文出自 “Linux革命” 博客,请务必保留此出处http://kaibinyuan.blog.51cto.com/7304008/1619672
标签:字符串
原文地址:http://kaibinyuan.blog.51cto.com/7304008/1619672