2013-10-14 54 views
4

在bash腳本中,我想從給定的字符串中提取變量字符串。我的意思是,我倒是想從一個字符串中提取字符串file.txt帶正則表達式的Bash子串

This is the file.txt from my folder. 

我想:

var=$(echo "This is the file.txt from my folder.") 
var=echo ${var##'This'} 
... 

,但我倒是喜歡,使其在一個更清潔的方式,使用exprsedawk命令。

感謝

編輯:

我找到了另一種方式(不過,與sed命令的回答是最好的一個對我來說):

var=$(echo 'This is the file.txt from my folder.') 
front=$(echo 'This is the ') 
back=$(echo ' from my folder.') 
var=${var##$front} 
var=${var%$back} 
echo $var 

回答

11

以下解決方案使用seds/(替代)刪除前後部分:

echo "This is the file.txt from my folder." | sed "s/^This is the \(.*\) from my folder.$/\1/" 

輸出:

file.txt 

\(\)包圍,我們要保留的部分。這被稱爲一個組。因爲它是我們在這個表達式中使用的第一個(也是唯一的)組,所以它是組1.我們稍後在替換字符串內部引用該組\1

^$標誌確保完整的字符串匹配。這只是在文件名包含"from my folder.""This is the"的特殊情況下才需要。

1

如果 'file.txt的' 是一個固定的字符串,並且不會改變,那麼你可以做這樣的:

var="This is the file.txt from my folder"

請注意,您不需要將字符串回顯給變量,只需在二進制'='運算符的右側輸入即可。

echo $var |sed -e 's/^.*\(file\.txt\).*$/\1/'

根據您的sed(1)版本,你可以,如果你有-r(擴展正則表達式)的選項鬆括號的轉義(1)的sed。

如果 'file.txt的' 變化,比你可以創建一個盡力而爲的基礎上的模式,如:

echo $var |sed -e 's/^.* \([^ ]\+\.[^ ]\+\) .*$/\1/'