Shell 处理字符串和{}操作
1. 获取变量的长度
获取字符串长度的方法大概有4种:(以hello world 为例)
- 
通过 wc -L$ echo "hello world" | wc -L 11
- 
通过 expr length string$ expr length "hello world" 11
- 
通过awk内置的length函数 $ echo "hello world" | awk '{print length($0)}' 11
- 
通过 echo ${#string_name}$ string='hello world' $ echo ${#string} 11
2. 截取变量 by {}操作
- 
#操作符 -- 从最左边开始到第一次出现子字符串的地方,全部删除$echo $string hello world $echo ${string#*l} lo world $echo ${string#*ll} o world $echo ${string#*llo} world $echo ${string#llo} hello world
注意: 这里需要用*来匹配,否则就像最后一个一样无效,另外倒数第二中把开头的空格去掉了,这个应该是shell的一种默认赋值,会将变量开头的空格去掉。例如:
$str1=" hello"
$echo $str1
hello
- 
##是从最左边开始匹配到最后出现子字符串的地方$echo ${string##*l} d
- 
%是从最右边开始匹配到第一个出现子字符串的地方,*号放在匹配子字符串的右边$echo ${string%l*} hello wor
- 
%%是从最右边开始匹配到最后出现子字符串的地方$echo ${string%%l*} he
- 
${string:m:n}操作
注意:
左边第一个下标用 0 表示
右边第一个下表用 0-1 表示,右边第二个用 0-2 表示, 依次类推 n 表示字符的个数,不是下标${string:3}这里的3表示从左边第4个开始
$echo $string
hello world
$echo ${string:0:2}
he
$echo ${string:0-2:2}
ld
$echo ${string:2}
llo world
3. 参数替换和扩展 -- by {} 操作
- 
${str-value}如果str没有被申明,则赋值value
- 
${str:-value}如果str没有被申明或者值为空,则赋值value$var= $echo ${var-helo} -- 此时变量var为空 $echo ${var:-helo} helo
- 
${str+value} 如果不管str为何值,均使用value作为默认值 
- 
${str:+value} 除非str为空,否则均使用value作为默认值 
- 
${str=value} 如果str没有被申明,则使用value作为默认值,同时将str赋值为value 
- 
${str:=value} 如果str没有被申明,或者为空,则使用value作为默认值,同时将str赋值为value 
- 
${str?value} 如果str没有被申明,输出value到STDERR 
- 
${str:?value} 如果str没有被申明,或者为空,输出value到STDERR 
- 
${!var}间接变量引用$echo $string hello world $str="string" $echo ${!str} hello world
- 
${!prefix*}匹配之前所有以prefix开头申明的变量
- 
${!prefix@}匹配之前所有以prefix开头申明的变量$cat test.sh c_var1="hello" c_var2="world" for c in ${!c_*}; do echo "${c}=${!c}" done $sh test.sh c_var1=hello c_var2=world
4. 字符串替换 -- by {}操作
- 
${string/str1/str2},用str2替换从左边数第一个str1
- 
${string//str1/str2},用str2替换全部str1
- 
${string/#str1/str2},如果string的前缀是str1,则将其替换为str2
- 
${string/%str1/str2},如果string的后缀是str1,则将其替换为str2$echo ${string/l/s} heslo world $echo ${string//l/s} hesso worsd $echo ${string/#he/h} hllo world $echo ${string/%ld/d} hello word
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号