標籤:style http io ar os sp on 2014 cti
今天總結了下Shell指令碼的幾種處理字串的方式,封裝了幾個基本的字串處理函數。
代碼(string.inc)如下:
#!/bin/sh#一個測試函數#輸入:無function str_testfunc(){ echo "這是一個測試函數"}#擷取字串長度#輸入:字串function str_length(){ echo `expr length $1`}#擷取字串子串#輸入:字串 截取起始位置#輸入:字串 截取起始位置 截取長度function str_substring(){ if [ $# -eq 2 ]; then len=`str_length $1` echo `expr substr $1 $2 $len` elif [ $# -eq 3 ]; then echo `expr substr $1 $2 $3` else echo fi}#替換子串#輸入:字串 要替換子串 用於替換的字串function str_replace(){ echo ${1//$2/$3}}#按給定字元截取字串#輸入:字串 用於劃分子串的字元function str_split(){ i=1 while [ true ]; do temp=`echo "$1" | cut -d "$2" -f$i` if [ "$temp" != "" ]; then ((i++)) echo $temp else break fi done}#刪除字串前後空格#輸入:字串function str_trim(){ echo `echo "$1"`}#找出給定子串在字串中出現的位置#輸入:字串 要搜尋的子串function str_indexof(){ echo `expr index $1 $2`}#將字串中字元全部轉換為大寫#輸入:字串function str_toupper(){ echo $(echo $1 | tr ‘[a-z]‘ ‘[A-Z]‘)}#將字串中字元全部轉換為小寫#輸入:字串function str_tolower(){ echo $(echo $1 | tr ‘[A-Z]‘ ‘[a-z]‘)}
呼叫指令碼(a.sh)如下:
#!/bin/sh. ./string.incstr_testfunc#擷取字串長度echo 字串"abcdefgh"長度為:`str_length "abcdefgh"`"|END"#擷取字串子串echo 字串"abcdefgh"截取子串:`str_substring "abcdefgh" 4 3`"|END"echo 字串"abcdefgh"截取子串:`str_substring "abcdefgh" 4`"|END"#替換字串echo 把abcdebcdf中的bcd替換為f:`str_replace "abcdebcdf" "bcd" "x"`"|END"#截取字串echo 截取字串1:`str_split "a b c d e f g" " "`"|END"echo 截取字串2:`str_split "a:b:c:d:e:f:g" ":"`"|END"#去掉前後空格echo " ab cd "去掉前後空格:`str_trim " ab cd "`"|END"echo abcdefg中bcde第一次出現的位置:`str_indexof "abcbcbd" "bcb"`"|END"#字串中字母大小寫轉換echo "abcdefgh"轉大寫:`str_toupper "abcdefgh"`"|END"echo "ABCDEFGH"轉小寫:`str_tolower "ABCDEFGH"`"|END"exit 0
運行:
END
Shell指令碼:幾個基本的字串處理方法總結