天天看點

SHELL中如何獲得指定字元的位置及正确的截取動作

柳鲲鵬

其實這個位置好擷取,使用中,發現結果總是不對。問題在于這個變量怎麼儲存。正确做法:

text="123 456"
# 關鍵!隻有這樣寫,才能儲存下來,并在之後的操作中使用。
pos=`expr index "$text" " "`
echo ---$pos
 
# 截取:
head=`expr substr "$text" 1 $pos`
echo $head
 
# cut也可以
echo $text | cut -c 1-$pos