脚本提取字符串的一部分

时间:2014-02-19 15:14:48

标签: shell

ns/APAC_BankTransfers_Publish/CMB/services/svcPublishBankTransfers/flow.xml

在上面的这一行和类似的行中,我想提取servicesflow.xml之间存在的任何内容,并将其保存到变量DIST。

输出应为svcPublishBankTransfers

3 个答案:

答案 0 :(得分:5)

使用POSIX中可用的参数扩展机制:

s=ns/APAC_BankTransfers_Publish/CMB/services/svcPublishBankTransfers/flow.xml
s=${s%/flow.xml}    # remove "/flow.xml"
s=${s##*/services/} # remove everything before "services"
echo "$s"

这样做的好处在于纯粹在进行中(比需要通过外部工具管道的方法更快),并且与所有POSIX外壳(灰,破折号,ksh等)兼容。

参考文献:

答案 1 :(得分:1)

使用BASH正则表达式:

s='ns/APAC_BankTransfers_Publish/CMB/services/svcPublishBankTransfers/flow.xml'
[[ "$s" =~ /([^/]+)/[^/]*$ ]] && echo "${BASH_REMATCH[1]}"
svcPublishBankTransfers

或者其他:

[[ "$s" =~ /services/([^/]+)/flow\.xml ]] && echo "${BASH_REMATCH[1]}"
svcPublishBankTransfers

答案 2 :(得分:0)

bash$ echo "ns/APAC_BankTransfers_Publish/CMB/services/svcPublishBankTransfers/flow.xml" | cut -d '/' -f 5
svcPublishBankTransfers
bash$