2016-01-21 49 views
-1

的sed我有一個字符串變量Short_name="This_is_test_string"刪除單詞的具體使用UNIX

我要輸出使用sedShort_name變量的子test_string

+0

你是說你有一個名爲'Short_name',其值是'變量」 This_is_test_string「'或一個變量的值是'Short_name =」This_is_test_string「'或其他?你爲什麼需要使用sed? –

回答

0

你不需要SED。 Bash parameter expansion會做:

$ Short_name="This_is_test_string" 
$ echo "${Short_name##*_is_}" 
test_string 

從字符串的開頭刪除所有內容幷包括最後「_is_」

1

像這樣:

echo 'Short_name="This_is_test_string"' | sed 's/.*_is_//;s/"//' 

其分解:

s   -- substitute command 
/   -- delimiter 
.*_is_  -- match this 
       .*  -- any character (.), as many as possible (*) 
       _is_ -- these 4 exact characters 
/   -- delimiter 
(nothing) -- what to replace any match with 
/   -- delimiter 
;   -- end this command, start another 
s   -- substitute command 
/   -- delimiter 
"   -- match this character 
/   -- delimiter 
(nothing) -- what to replace any match with 
/   -- delimiter 

 

[編輯]

的關鍵是搞清楚哪些模式符合您的需求(我還沒有很好的下站立)。也許是這樣的:

... | sed 's/.*[[:<:]]is[ _]*//;s/"//' 

的「刁鑽位」這裏是[[:<:]]這是一個「零寬度斷言」(在這種情況下「字的開始」),這使我們做的這樣的輸入錯誤的事情:

echo 'string2=is this it"' | sed 's/.*[[:<:]]is[ _]*//;s/"//' 

(通過保持我們從匹配 「是」,在 「本」)

+0

我剛剛嘗試使用下面的方式, string =「this_is_my_test_name」 final = $(echo $ {string} | sed's /^.* is _ //;')它給出了預期的輸出。但是,如果情形是一樣, 字符串2 =是 然後在下面的代碼無法正常工作, 最終= $(回聲$ {字符串} | sed中的/^.*$ {字符串2} _ //;') 如何使用變量string2? – Rock

+0

得到解決方案, final = $(echo $ {string} | sed's /^.*'$ o_string'_ //;') – Rock