Bash – extract string between double quotes

bashshell-scriptstring

I have requirement that i need to extract string using quotes. My string as follows.

"abcd efgh" "ijkl mnop" "qrst uvwxyz"

can you help me to get the string between second double quotes(ijkl mnop) using sed or grep command.

In other words if I say give me the string in first quotes I want the first string; if I say second string it should give me string between second double quotes and similarly third one also.

Best Answer

I am not sure how you want to input the string. This has the effect you want to achieve, but it might need to be modified according to how the string is entered:

aa() { echo $3 ; } ; aa "abcd efgh" "ijkl mnop" "qrst uvwxyz"

Edit: So, if it is in variable (it has to be defined with quoted ") :

AA="\"abcd efgh\" \"ijkl mnop\" \"qrst uvwxyz\""
echo $AA

then:

FIRST=`echo $AA| awk -F \" '{print $2}'`
SECOND=`echo $AA| awk -F \" '{print $4}'`
THIRD=`echo $AA| awk -F \" '{print $6}'`
echo $FIRST : $SECOND : $THIRD

as jasonwryan pointed out above. You said, you wanted to use sed, but it makes it unnecessary complex :

FIRST=`echo $AA| sed 's/^\"\([^\"]*\)\".*/\1/'`
SECOND=`echo $AA| sed 's/^\"[^\"]*\" \"\([^\"]*\)\".*/\1/'`
THIRD=`echo $AA| sed 's/^\"[^\"]*\" \"[^\"]*\" \"\([^\"]*\)\".*/\1/'`

Edit2: It is actually possible to achieve completely without sed,awk,perl,.. only with bash, using its "read" builtin function like this (echos are for debugging):

#!/bin/bash

aa() {
echo '$1'="$1"
IFS=\" read aaa FIRST bbb SECOND ccc THIRD ddd <<< "$1"
echo FIRST=$FIRST : SECOND=$SECOND : THIRD=$THIRD
}

AA="\"abcd efgh\" \"ijkl mnop\" \"qrst uvwxyz\""
echo '$AA'="$AA"
aa "$AA"
Related Question