歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux資訊 >> 更多Linux >> bash中字符串的處理

bash中字符串的處理

日期:2017/2/27 14:13:21   编辑:更多Linux
1.得到字符串長度方法一:$echo ${#variable}code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ echo ${#x} 14 方法二:$eXPr length "$variable"code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ expr length "$x" 14 方法三:$expr "$variable" : ".*"code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ expr "$x" : ".*" 14 2.查找字符串子串位置方法:$expr index "$variable" "substring"code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ expr index "$x" "is" 3 zhyfly: ~$ expr index "$x" "t" 1 (ps:如果出現重復,好象只能查到第一個,第二個,第三個,...,怎麼查到呢???)3.得到字符串子字符串方法一:$echo ${variable:position:length}code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ echo ${x:1:5} his i 方法二:$expr substr "$variable" startposition lengthcode: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ expr substr "$x" 1 5 this (ps:注意方法一和方法二中位置的區別!)4.匹配正則表達式之匹配長度方法:$expr match "$x" "string"code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ expr match "$x" "his" 0 zhyfly: ~$ expr match "$x" "this" 4 zhyfly: ~$ expr match "$x" "." 1 5.字符串的掐頭去尾方法:$echo ${variable#startletter*endletter} # #表示掐頭,因為鍵盤上#在$前面,一個表示最小匹配$echo ${variable##tartletter*endletter} 兩個表示最大匹配$echo ${variable%startletter*endletter} # %表示去尾,因為鍵盤上%在$後面,一個表示最小匹配$echo ${variable%%startletter*endletter} 兩個表示最大匹配code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ echo ${x#t} his is a test zhyfly: ~$ echo ${x#t*h} is is a test zhyfly: ~$ echo ${x#t*s} is a test zhyfly: ~$ echo ${x##t*s} t zhyfly: ~$ echo ${x%t} this is a tes zhyfly: ~$ echo ${x%s*t} this is a te zhyfly: ~$ echo ${x%e*t} this is a t zhyfly: ~$ echo ${x%%i*t} th 6.字符(串)的替換方法:$echo ${variable/oldletter/newletter} #替換一個$echo ${variable//oldletter/newletter} #替換所有code: PHP 代碼: zhyfly: ~$ x="this is a test" zhyfly: ~$ echo ${x/i/m} thms is a test zhyfly: ~$ echo ${x//i/m} thms ms a test




Copyright © Linux教程網 All Rights Reserved