String between quotes

Hi,

Need to capture a string between 1st & last quote.

String can be anything like
a b "c" d e
Output: c
a "b c" d e
Output: b c
a "b c" d "e" f
Output: b c d e

sed 's/.*"\(.*\)".*/\1/g'
Above helps me to find the string between last quote.
Need to find the string between 1st & last quote.

echo 'a "b c" d "e" f' | sed 's/[^"]*\"\(.*\)\".*/\1/; s/\"//g'

Try like...

echo 'a b "c" d e ' | grep -Po '".*?"'

Goodie
Lemme try to get this.

[^"]*
Takes care of all character apart from "

sed (.) starts matching from backward
\"\(.*\)\".

So the 1st segment tells there shouldn't be any " before that.

Am i right?

If you are in ksh then you can slice the strings with the following:-

#!/bin/ksh

MYSTRING="a b c d e"            # Quoting to set the variable only. Quotes do not form part of string
TEMPVAR="${MYSTRING#*\"}" # Cut off everything before first quote - no effect
OUTPUT="${TEMPVAR%\"*}"   # Cut off everything after last quote - no effect
echo $OUTPUT

MYSTRING="a b \"c\" d e"            # Escaped quotes do form part of string
TEMPVAR="${MYSTRING#*\"}" # Cut off everything before first quote
OUTPUT="${TEMPVAR%\"*}"   # Cut off everything after last quote
echo $OUTPUT

The last criteria is a bit awkward though. The output you suggest ignores the fact that your string may have embedded quotes in it. Do you not want to know these exist?

If not, then append | tr -d "\"" to the echo $OUTPUT statement.

I hope that this helps.

Robin
Liverpool/Blackburn
UK

awk -f '"' '{$1=$NF=""}1' file

Try

sed -n 's/^[^"]*"\(.*\)"[^"]*$/\1/p' <filename>|tr -d '"'

The thing is, I find both sed & awk a bit heavy to fire up on the CPU if this is a repetitive processes. Of course, if the logic can be changed so that sed or awk can process a single large file, then that should be better.

Robin