Home > OS >  bash read between two strings using parameter expansion expression
bash read between two strings using parameter expansion expression

Time:12-13

This is how my input string looks like:

INPUT_STRING="{/p1/p2=grabthistext}"

I want to print grabthistext from the INPUT_STRING.

I tried echo "${INPUT_STRING##*=}" which prints grabthistext}

How do I read only grabthistext using parameter expansion expression?

CodePudding user response:

If you really want a single parameter expansion then you can use:

#!/bin/bash
shopt -s extglob

INPUT_STRING="{/p1/p2=grabthistext}"

echo "${INPUT_STRING//@(*=|\})}"
grabthistext

I would use a bash regex though:

#!/bin/bash

INPUT_STRING="{/p1/p2=grabthistext}"

[[ $INPUT_STRING =~ =(.*)} ]] && echo "${BASH_REMATCH[1]}"
grabthistext

CodePudding user response:

temp="${INPUT_STRING##*=}" 
echo "${temp%\}}"
grabthistext

CodePudding user response:

You can do it in two steps: first extract the fragment after = as you already did, and store it in a new variable. Then use the same technique to remove the undesired } suffix:

INPUT_STRING="{/p1/p2=grabthistext}"
TEMP_STRING=${INPUT_STRING##*=}
OUTPUT_STRING=${TEMP_STRING%\}}

echo "$OUTPUT_STRING"
# grabthistext

Check it online.

  • Related