基本操作
表达式 | 含义 |
${#string} | $string的长度 |
${string:position} | 在$string中, 从位置$position开始提取子串 |
${string:position:length} | 在$string中, 从位置$position开始提取长度为$length的子串 |
${string#substring} | 从变量$string的开头, 删除最短匹配$substring的子串 |
${string##substring} | 从变量$string的开头, 删除最长匹配$substring的子串 |
${string%substring} | 从变量$string的结尾, 删除最短匹配$substring的子串 |
${string%%substring} | 从变量$string的结尾, 删除最长匹配$substring的子串 |
${string/substring/replacement} | 使用$replacement, 来代替第一个匹配的$substring |
${string//substring/replacement} | 使用$replacement, 代替所有匹配的$substring |
${string/#substring/replacement} | 如果$string的前缀匹配$substring, 那么就用$replacement来代替匹配到的$substring |
${string/%substring/replacement} | 如果$string的后缀匹配$substring, 那么就用$replacement来代替匹配到的$substring |
应用场景
判断字符串是否存在包含关系
#! /bin/bash
string1="test"
string2="te"
#方法1(判断string1是否以string2开头)
if [ ${string1:0:2} = ${string2} ]
then
echo "1:include"
fi
#方法2(判断string1是否包含string2)
echo "${string1}" | grep -q "${string2}"
if [ $? -eq 0 ]
then
echo "2:include"
fi
string1="test"
string2="te"
#方法1(判断string1是否以string2开头)
if [ ${string1:0:2} = ${string2} ]
then
echo "1:include"
fi
#方法2(判断string1是否包含string2)
echo "${string1}" | grep -q "${string2}"
if [ $? -eq 0 ]
then
echo "2:include"
fi
字符串删除
[root@localhost ~]$ test='c:/windows/boot.ini'[root@localhost ~]$ echo ${test#/}
c:/windows/boot.ini
[root@localhost ~]$ echo ${test#*/}
windows/boot.ini
[root@localhost ~]$ echo ${test##*/}
boot.ini
[root@localhost ~]$ echo ${test%/*}
c:/windows
[root@localhost ~]$ echo ${test%%/*}
${变量名#substring正则表达式}从字符串开头开始配备substring,删除匹配上的表达式。
${变量名%substring正则表达式}从字符串结尾开始配备substring,删除匹配上的表达式。
注意:${test##*/},${test%/*} 分别是得到文件名,或者目录地址最简单方法。
[root@localhost ~]$ echo ${test/\//\\}
c:\windows/boot.ini
[root@localhost ~]$ echo ${test//\//\\}
c:\windows\boot.ini
字符串替换
[root@localhost ~]$ test='c:/windows/boot.ini'[root@localhost ~]$ echo ${test/\//\\}
c:\windows/boot.ini
[root@localhost ~]$ echo ${test//\//\\}
c:\windows\boot.ini
${变量/查找/替换值} 一个“/”表示替换第一个,”//”表示替换所有,当查找中出现了:”/”请加转义符”\/”表示。
性能比较
在shell中,通过awk,sed,expr 等都可以实现,字符串上述操作。下面我们进行性能比较。[root@localhost ~]$ test='c:/windows/boot.ini'
[root@localhost ~]$ time for i in $(seq 10000);do a=${#test};done;
[root@localhost ~]$ time for i in $(seq 10000);do a=${#test};done;
real 0m0.173s
user 0m0.139s
sys 0m0.004s
[root@localhost ~]$ time for i in $(seq 10000);do a=$(expr length $test);done;
real 0m9.734s
user 0m1.628s
速度相差上百倍,调用外部命令处理,与内置操作符性能相差非常大。在shell编程中,尽量用内置操作符或者函数完成。使用awk,sed类似会出现这样结果。
user 0m0.139s
sys 0m0.004s
[root@localhost ~]$ time for i in $(seq 10000);do a=$(expr length $test);done;
real 0m9.734s
user 0m1.628s
速度相差上百倍,调用外部命令处理,与内置操作符性能相差非常大。在shell编程中,尽量用内置操作符或者函数完成。使用awk,sed类似会出现这样结果。