Skip to main content
added parameter expansion option; added the search term back in, to match the expected output; put the parenthesis in a smarter place for the regex matching
Source Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 265

Since you tagged bash:

[[ $string =~ Icecream([^Icecream[^ ]*) ]] && trail=$BASH_REMATCH[1]result=${BASH_REMATCH[1]}

More generally, for a search term in $search:

[[ $string =~ $search([^$search[^ ]*) ]] && trail=$BASH_REMATCH[1]result=${BASH_REMATCH[1]}

... or with parameter expansion:

# remove any leading text up to -and through- the search text:
x=${string##*$search}

# remove any trailing space onwards
result=$search${x%% *}

Since you tagged bash:

[[ $string =~ Icecream([^ ]*) ]] && trail=$BASH_REMATCH[1]

More generally, for a search term in $search:

[[ $string =~ $search([^ ]*) ]] && trail=$BASH_REMATCH[1]

Since you tagged bash:

[[ $string =~ (Icecream[^ ]*) ]] && result=${BASH_REMATCH[1]}

More generally, for a search term in $search:

[[ $string =~ ($search[^ ]*) ]] && result=${BASH_REMATCH[1]}

... or with parameter expansion:

# remove any leading text up to -and through- the search text:
x=${string##*$search}

# remove any trailing space onwards
result=$search${x%% *}
Source Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 265

Since you tagged bash:

[[ $string =~ Icecream([^ ]*) ]] && trail=$BASH_REMATCH[1]

More generally, for a search term in $search:

[[ $string =~ $search([^ ]*) ]] && trail=$BASH_REMATCH[1]