Nathan Campos
Nathan Campos

Reputation: 29507

Get An Specified Match Under a String

I'm trying to match the contents of a string that contains sequences of quotes using Shell Script, at the time the far I got was this:

et="\"He\" \"llo\""
echo $et | sed -e '/\"(.*?)\"/g'

Which returns this:

"He" "llo"

But I don't want the quote marks to appear on the result, also how can I echo only the first, or the second, or the third, etc. match?

Upvotes: 0

Views: 77

Answers (4)

user982733
user982733

Reputation:

You can also do something like this:

[srikanth@myhost ~]$ echo "\"He\" \"llo\"" | awk ' { match($0,/([A-Za-z]+)[" ]+([A-Za-z]+)/,a); print a[1]","a[2]} '
He,llo

Upvotes: 0

SiegeX
SiegeX

Reputation: 140477

This is much simpler with awk since you can specify the double-quote to be the field separator.

$ et='"He" "llo"'
$ awk -F'"' '{print $2}' <<<$et
He
$ awk -F'"' '{print $4}' <<<$et
llo

Note: This is also scalable and the strings fields will be in multiples of two, i.e $2, $4, $6, etc.

Upvotes: 0

fge
fge

Reputation: 121820

Provided that what is wanted is only the text between the first pair of quotes, here is a solution with perl:

echo $et | perl -ne '/"[^"]+"/ and print "$&\n";'

This will also handle quotes witin quotes if they are preceded by a backslash:

echo $et | perl -ne '/"[^"\\]+(\\.[^"]*)*"/ and print "$&\n";'

Upvotes: 1

Mattias Wadman
Mattias Wadman

Reputation: 11425

sed -e 's/"\([^"]*\)"/\1/g' will remove quotes around balanced " quotes. To only show the first, second match etc with sed you probably have to make different capture groups.

$ echo '"1" "2" "3"' | sed -e 's/"\([^"]*\)" "\([^"]*\)" "\([^"]*\)"/\2/g'
2
$

Upvotes: 1

Related Questions