参考链接:http://justcoding.iteye.com/blog/1963463
字符串读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #!/bin/bash
var="Hello" DEFAULT="FQK" OTHER="World" ERR_MSG="Sorry"
echo ${var-$DEFAULT} echo ${undefined_var-$DEFAULT} echo ${undefined_var} echo ${var+$OTHER} echo ${undefined_var+$OTHER} echo ${var=$DEFAULT} echo ${undefined_var=$DEFAULT} echo ${var} echo ${undefined_var}
unset undefined_var echo ${undefined_var?$ERR_MSG}
|
1 2 3 4 5 6 7 8 9 10 11 12
| bogon:Shell fang$ ./read_str.sh Hello FQK
World
Hello FQK Hello FQK ./read_str.sh: line 24: undefined_var: Sorry bogon:Shell fang$
|
字符串操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #!/bin/bash
string="Hello world!"
# ${#string} $string的长度 echo ${#string} # 12
# ${string:position} 在$string中, 从位置position开始提取子串 echo ${string:3} # lo world!
# ${string:position:length} 在$string中, 从位置position开始提取长度为length的子串 echo ${string:3:5} # lo wo
# ${string#substring} 从变量$string的开头, 删除最短匹配substring的子串 # ${string##substring} 从变量$string的开头, 删除最长匹配substring的子串 echo ${string#H*l} # o world! echo ${string##H*l} # d!
# ${string%substring} 从变量$string的结尾, 删除最短匹配substring的子串 # ${string%%substring} 从变量$string的结尾, 删除最长匹配substring的子串 echo ${string%o*!} # Hello w echo ${string%%o*!} # Hell
# ${string/substring/replacement} 使用replacement, 来代替第一个匹配的substring # ${string # ${string/#substring/replacement} 如果$string的前缀匹配substring, 那么就用replacement来代替匹配到的substring # ${string/%substring/replacement} 如果$string的后缀匹配substring, 那么就用replacement来代替匹配到的substring echo ${string
|
1 2 3 4 5 6 7 8 9 10
| bogon:Shell fang$ ./operate_str.sh 12 lo world! lo wo lo world! d! Hello w Hell Hello### bogon:Shell fang$
|