Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting a string between two quotes in bash

Tags:

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.

like image 497
Vik Avatar asked Feb 25 '16 19:02

Vik


People also ask

How do you slice a string in bash?

Using the cut Command Specifying the character index isn't the only way to extract a substring. You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.

How do you escape double quotes in shell?

' appearing in double quotes is escaped using a backslash. The backslash preceding the ' ! ' is not removed. The special parameters ' * ' and ' @ ' have special meaning when in double quotes (see Shell Parameter Expansion).

How do you put quotes in a string in bash?

For example string="single quote: ' double quote: "'"'" end of string" . This works because quoted strings next to each other are considered a single string and you can switch between single and double quote strings within those parts.


2 Answers

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"
like image 171
Charles Duffy Avatar answered Oct 04 '22 17:10

Charles Duffy


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
like image 41
Arton Dorneles Avatar answered Oct 04 '22 17:10

Arton Dorneles