2011-08-01 112 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$//' 

这产生由你想要的部分的输出。反向或根据需要重定向。