ns/APAC_BankTransfers_Publish/CMB/services/svcPublishBankTransfers/flow.xml
在上面的行和类似的行中,我想提取services
和flow.xml
之间存在的任何内容,并将其保存到变量 DIST 中。
输出应svcPublishBankTransfers
。
使用 POSIX sh 中可用的参数扩展机制:
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等)兼容。
引用:
- BashFAQ #100 ("如何在 bash 中进行字符串操作?
- BashFAQ #73 ("如何使用参数扩展?如何获取子字符串?
使用 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
bash$ echo "ns/APAC_BankTransfers_Publish/CMB/services/svcPublishBankTransfers/flow.xml" | cut -d '/' -f 5
svcPublishBankTransfers
bash$