Vik
Vik

Reputation: 9319

extracting a string between two quotes in bash

I have example string like Test "checkin_resumestorevisit - Online_V2.mt" Run

and i want to extract the text between the two quotes in bash. I tried using command like

SUBSTRING=${echo $SUBSTRING| cut -d'"' -f 1 }

but it fails with error: bad substitution.

Upvotes: 19

Views: 32873

Answers (3)

bufh
bufh

Reputation: 3420

Other weird ideas to not let @arton-dorneles alone :^)

But my favourite is @charles-duffy answer.

[[ "$SUBSTRING" =~ \"(.*)\" ]] && SUBSTRING="${BASH_REMATCH[1]}"

IFS=\" read -r _ SUBSTRING _ <<<"$SUBSTRING"

# bonus, match either ' or " by pair
SUBSTRING=$(echo "$SUBSTRING" | sed -r "s/.*?([\"'])(.*)\1.*/\2/")

Note that bash create a temporary file for "here string" (<<<) as it does for here documents.

Edit

It took me way too long to fully understand Charles Duffy critics; for readers, this could be when:

SUBSTRING='*"inside text" outside text'

In this scenario, the following would be unsafe because the star would be expanded, listing files and moving the desired result index:

IFS=\" eval '_=($SUBSTRING);SUBSTRING="${_[1]}"'

IFS=\" read -ra _ <<<"$SUBSTRING";SUBSTRING=${_[1]}

Upvotes: 1

Arton Dorneles
Arton Dorneles

Reputation: 1709

In order to extract the substring between quotes you can use one of these alternatives:

Alternative 1:

SUBSTRING=`echo "$SUBSTRING" | cut -d'"' -f 2`

Alternative 2:

SUBSTRING=`echo "$SUBSTRING" | awk -F'"' '{print $2}'`

Alternative 3:

set -f;IFS='"'; SUBSTRING=($SUBSTRING); SUBSTRING=${SUBSTRING[1]};set +f

Upvotes: 34

Charles Duffy
Charles Duffy

Reputation: 296049

If you want to extract content between the first " and the last ":

s='Test "checkin_resumestorevisit - Online_V2.mt" Run'
s=${s#*'"'}; s=${s%'"'*}
echo "$s"

Upvotes: 5

Related Questions