bash read between two strings using parameter expansion expression

82 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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
0
On
temp="${INPUT_STRING##*=}" 
echo "${temp%\}}"
grabthistext
0
On

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.