shell字符串处理
生活随笔
收集整理的這篇文章主要介紹了
shell字符串处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉自:http://mcuos.com/thread-2357-1-1.html
?
一、構造字符串
直接構造
STR_ZERO=hello
STR_FIRST="i am a string"
STR_SECOND='success'
重復多次
#repeat the first parm($1) by $2 times
strRepeat()
{
local x=$2
if [ "$x" == "" ]; then
x=0
fi
local STR_TEMP=""
while [ $x -ge 1 ];
do
STR_TEMP=`printf "%s%s" "$STR_TEMP" "$1"`
x=`expr $x - 1`
done
echo $STR_TEMP
}
舉例:
STR_REPEAT=`strRepeat "$USER_NAME" 3`
echo "repeat = $STR_REPEAT"
二、賦值與拷貝
直接賦值
與構造字符串一樣
USER_NAME=terry
從變量賦值
ALIASE_NAME=$USER_NAME
三、聯接
直接聯接兩個字符串
STR_TEMP=`printf "%s%s" "$STR_ZERO" "$USER_NAME"`
使用printf可以進行更復雜的聯接
四、求長
求字符數(char)
COUNT_CHAR=`echo "$STR_FIRST" | wc -m`
echo $COUNT_CHAR
求字節數(byte)
COUNT_BYTE=`echo "$STR_FIRST" | wc -c`
echo $COUNT_BYTE
求字數(word)
COUNT_WORD=`echo "$STR_FIRST" | wc -w`
echo $COUNT_WORD
五、比較
相等比較
str1 = str2
不等比較
str1 != str2
舉例:
if [ "$USER_NAME" = "terry" ]; then
echo "I am terry"
fi
小于比較
#return 0 if the two string is equal, return 1 if $1 < $2, else2strCompare() { local x=0 if [ "$1" != "$2" ]; then x=2localTEMP=`printf "%s/n%s" "$1" "$2"` local TEMP2=`(echo "$1"; echo"$2") |sort` if [ "$TEMP" = "$TEMP2" ]; then x=1 fi fi echo $x }
六、測試
判空
-z str
判非空
-n str
是否為數字
# return 0 if the string is num, otherwise 1
strIsNum()
{
local RET=1
if [ -n "$1" ]; then
local STR_TEMP=`echo "$1" | sed 's/[0-9]//g'`
if [ -z "$STR_TEMP" ]; then
RET=0
fi
fi
echo $RET
}
舉例:
if [ -n "$USER_NAME" ]; then
echo "my name is NOT empty"
fi
echo `strIsNum "9980"`
七、分割
以符號+為準,將字符分割為左右兩部分
使用sed
舉例:
命令 date --rfc-3339 seconds 的輸出為
2007-04-14 15:09:47+08:00
取其+左邊的部分
date --rfc-3339 seconds | sed 's/+[0-9][0-9]:[0-9][0-9]//g'
輸出為
2007-04-14 15:09:47
取+右邊的部分
date --rfc-3339 seconds | sed 's/.*+//g'
輸出為
08:00
以空格為分割符的字符串分割
使用awk
舉例:
STR_FRUIT="Banana 0.89 100"
取第3字段
echo $STR_FRUIT | awk '{ print $3; }'
八、子字符串
字符串1是否為字符串2的子字符串
# return 0 is $1 is substring of $2, otherwise 1
strIsSubstring()
{
local x=1
case "$2" in
*$1*) x=0;;
esac
echo $x
}
Shell字符串截取
一、Linux shell 截取字符變量的前8位,有方法如下:1.expr substr “$a” 1 8
2.echo $a|awk ‘{print substr(,1,8)}’
3.echo $a|cut -c1-8
4.echo $
5.expr $a : ‘/(.//).*’
6.echo $a|dd bs=1 count=8 2>/dev/null
二、按指定的字符串截取
1、第一種方法:
- ${varible##*string} 從左向右截取最后一個string后的字符串
- ${varible#*string}從左向右截取第一個string后的字符串
- ${varible%%string*}從右向左截取最后一個string后的字符串
- ${varible%string*}從右向左截取第一個string后的字符串
例子:
$ MYVAR=foodforthought.jpg
$ echo ${MYVAR##*fo}
rthought.jpg
$ echo ${MYVAR#*fo}
odforthought.jpg
2、第二種方法:${varible:n1:n2}:截取變量varible從n1到n2之間的字符串。
可以根據特定字符偏移和長度,使用另一種形式的變量擴展,來選擇特定子字符串。試著在 bash 中輸入以下行:
$ EXCLAIM=cowabunga
$ echo ${EXCLAIM:0:3}
cow
$ echo ${EXCLAIM:3:7}
abunga
這種形式的字符串截斷非常簡便,只需用冒號分開來指定起始字符和子字符串長度。
三、按照指定要求分割:
比如獲取后綴名
ls -al | cut -d “.” -f2
總結
以上是生活随笔為你收集整理的shell字符串处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell脚本判断输入参数个数
- 下一篇: 大学物理相干波的问题