shell 字符串操作(长度,查找,替换)详解

2019-09-23 09:51:54丽君

如果abc 没有声明“="还会给abc赋值。

[chengmo@localhost ~]$ var1=11;var2=12;var3=
[chengmo@localhost ~]$ echo${!v@}
var1 var2 var3
[chengmo@localhost ~]$ echo ${!v*}
var1 var2 var3

${!varprefix*}与${!varprefix@}相似,可以通过变量名前缀字符,搜索已经定义的变量,无论是否为空值。

二、字符串操作(长度,读取,替换)

表达式

含义

${#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


说明:"* $substring”可以是一个正则表达式.

1.长度

[web97@salewell97 ~]$ test='I love china'
[web97@salewell97 ~]$ echo ${#test}
12
${#变量名}得到字符串长度

2.截取字串

[chengmo@localhost ~]$ test='I love china'
[chengmo@localhost ~]$ echo ${test:5}
e china
[chengmo@localhost ~]$ echo ${test:5:10}
e china
${变量名:起始:长度}得到子字符串

3.字符串删除

[chengmo@localhost ~]$ test='c:/windows/boot.ini'
[chengmo@localhost ~]$ echo ${test#/}
c:/windows/boot.ini
[chengmo@localhost ~]$ echo ${test#*/}
windows/boot.ini
[chengmo@localhost ~]$ echo ${test##*/}
boot.ini
[chengmo@localhost ~]$ echo ${test%/*}
c:/windows
[chengmo@localhost ~]$ echo ${test%%/*}
${变量名#substring正则表达式}从字符串开头开始配备substring,删除匹配上的表达式。
${变量名%substring正则表达式}从字符串结尾开始配备substring,删除匹配上的表达式。