Prashast
Prashast

Reputation: 57

Script to extract a part of string

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

In the above line and similar lines like this I want to extract whatever is present in between services and flow.xml and save it to a variable DIST.

The output should be svcPublishBankTransfers.

Upvotes: 1

Views: 74

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295403

Using parameter expansion mechanisms available in 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"

This has the advantages of being purely in-process (so faster than approaches that require piping through an external tool), and compatible with all POSIX shells (ash, dash, ksh, etc).

References:

Upvotes: 5

C.B.
C.B.

Reputation: 8326

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

Upvotes: 0

anubhava
anubhava

Reputation: 785156

Using BASH regex:

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

OR else:

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

Upvotes: 1

Related Questions