aksamit
aksamit

Reputation: 2453

Retrieve matching element from string

Using bash I have a string that holds my deployed applications:

APPS="myapp-a-1.0.war myapp-b-1.1.war myapp-c-1.2-SNAPSHOT.war"

I can determine whether a specific app is deployed:

if [[ "$APPS" == *myapp-a* ]]
then
    echo "myapp-a is deployed, but we don't know the version."
fi

How can I retrieve the complete matching word (application with version) given that I only have the words prefix (application name, e.g. 'myapp-a')?

Upvotes: 1

Views: 47

Answers (2)

user904990
user904990

Reputation:

as simple as:

if [[ "$APPS" =~ myapp\-a([^war]*)war ]]; then
  echo "${BASH_REMATCH[0]} deployed"
fi

result in:

myapp-a-1.0.war deployed

if you need only version:

if [[ "$APPS" =~ myapp\-a([^war]*)war ]]; then
  echo "${BASH_REMATCH[1]} deployed"
fi

result in:

-1.0. deployed

if you need version without artefacts like dashes, dots:

if [[ "$APPS" =~ myapp\-a\-([^war]*)\.war ]]; then
  echo "${BASH_REMATCH[1]} deployed"
fi

result in:

1.0 deployed

Upvotes: 1

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76611

You can loop over your variable (provided you don't quote it):

for app in ${APPS}; do
  if [[ "${app}" == myapp-a* ]]; then
    echo ${app}
  fi
done

Upvotes: 1

Related Questions