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
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"
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
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.
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]}