簡體   English   中英

在字符串的開頭和結尾處修剪字母

[英]trim letters at the beginning and the end of a string

# trim the beginning "t"
echo "test"|sed "s/^t//g" 
est

# trim the ending "t"
echo "test"|sed "s/t$//g"
tes

# trim both the beginning and ending "t"
echo "test"|sed "s/(^t)|(t$)//g"
test

為什么第三人失敗了? 我該如何運作?

您需要為此使用擴展的正則表達式: -r

$ echo "test"|sed -r "s/(^t)|(t$)//g"
es

來自man sed

-r ,--regexp擴展

在腳本中使用擴展的正則表達式。

或者,您也可以逃避所有正則表達式條件,例如Etan Reisner建議

$ echo test | sed 's/\(^t\)\|\(t$\)//g' 
es

注意,您也可以使用-e指示多個命令:

$ echo "test"|sed -e "s/^t//" -e "s/t$//"
es

您可以簡單地使用它,

$ echo test | sed 's/^t\|t$//g'
es

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM