2011-08-01 111 views
3

在我的bash腳本,我有文件名類似bash腳本正則表達式匹配

files=("site_hello.xml" "site_test.xml" "site_live.xml") 

我需要提取下劃線和.xml擴展名之間的字符數組,這樣我可以遍歷他們在使用一個函數。

如果這是蟒蛇,我可能會使用類似

re.match("site_(.*)\.xml") 

然後抽取第一個匹配的組。

不幸的是,這個項目需要在bash中,所以 - 如何在bash腳本中做這種事情?我對grep或sed或awk不太瞭解。

回答

2
[email protected] ~ 
$ VAR=`echo "site_hello.xml" | sed -e 's/.*_\(.*\)\.xml/\1/g'` 

[email protected] ~ 
$ echo $VAR 
hello 

[email protected] ~ 
$ 

這是回答您的問題嗎?

只需通過運行變量的sed在反引號(``)

我不記得在bash數組語法,但我猜你應該知道不夠好自己,如果你正在編寫的bash;)

如果不清楚,不要猶豫再問一次。 :)

5

類似下面應該工作

files2=(${files[@]#site_}) #Strip the leading site_ from each element 
files3=(${files2[@]%.xml}) #Strip the trailing .xml 

編輯:糾正這兩個錯別字後,它似乎工作:)

+0

順便說一句,這些替換選項都記錄在這裏:http://tldp.org/LDP/abs/html/arrays.html – jkerian

0

我會用cut拆分字符串。

for i in site_hello.xml site_test.xml site_live.xml; do echo $i | cut -d'.' -f1 | cut -d'_' -f2; done 

這也可以在awk完成:

for i in site_hello.xml site_test.xml site_live.xml; do echo $i | awk -F'.' '{print $1}' | awk -F'_' '{print $2}'; done 
0

如果你使用數組,你可能不應該使用bash。

一個更合適的例子是沃爾德

ls site_*.xml | sed 's/^site_//' | sed 's/\.xml$//' 

這產生由你想要的部分的輸出。反向或根據需要重定向。