轉自:http://www.cnblogs.com/kinga/p/5772566.html
Shell
第一種:
${parameter%word} 最小限度從后面截掉word
${parameter%%word} 最大限度從后面截掉word
${parameter#word} 最小限度從前面截掉word
${parameter##word} 最大限度從前面截掉word
word可以是一個具體的字符串,也可以是一個模式字符串。
例子:
str='http://www.你的域名.com/cut-string.html'
echo ${str%/*}
結果:http://www.你的域名.com
echo ${str%%/*}
結果:http:
echo ${str#*//}
結果:www.你的域名.com/cut-string.html
echo ${str##*/}
結果:cut-string.html
第二種:
${variable:n1:n2}:截取變量variable從左邊起索引n1開始的n2個字符。n1表示索引,索引從0開始;n2表示截取的字符個數。
變種如下:
${variable:n1}:截取變量variable從左邊起索引n1開始的所有字符。
${variable:0-n1:n2}:截取變量variable從右邊起第n1個字符開始的n2個字符。
${variable:0-n1:n2}:截取變量variable從右邊起第n1個字符開始的所有字符。
例子:
variable='http://www.你的域名.com/cut-string.html'
echo ${variable:0:4}
結果:http
echo ${variable:7}
結果:www.你的域名.com/cut-string.html
echo ${variable:0-15:10}
結果:cut-string
echo ${variable:0-15}
結果:cut-string.html
第三種:
借助其他shell命令,如cut
cut命令的選項主要有以下幾個:
echo $variable | cut -c1-4
結果:http
echo $variable | cut -c8-
結果:www.你的域名.com/cut-string.html
echo $variable | cut -d":" -f1
結果:http