St.Antario
St.Antario

Reputation: 27385

Extract string from square brackets and quotes

I was trying to extract strings of the following form:

[["abc"]] --> abc

So I wrote echo "[[\"abc\"]]" | sed -e 's/\[\[\"//g' | sed -e 's/\"\]\]//g'

And it works fine but looks extremely ugly. I'm pretty much sure that there should be a neater solution for such a simple case?

Can you please advice some sed or awk enhancement for that?

Upvotes: 1

Views: 752

Answers (4)

Travis Clarke
Travis Clarke

Reputation: 6671

For sed, one option to make your command a bit more succinct is to use a capture group along with a backreference:

echo "[[\"abc\"]]" | sed -e 's/\[\["\(.*\)"\]\]/\1/g'
> abc

Upvotes: 2

karakfa
karakfa

Reputation: 67487

just remove the unwanted chars

$ echo "[[\"abc\"]]" | tr -d '[]"'
abc

Upvotes: 2

Lewis M
Lewis M

Reputation: 548

If you are just looking for what is between the double-quotes, try this

echo '[["abc"]]' | awk -F\" '{print $2}'

Hope this helps

Upvotes: 3

Barmar
Barmar

Reputation: 780929

You can use a single replacement with a capture group:

echo '[["abc"]]' | sed 's/\[\["\([^"]*\)"\]\]/\1/g'

You also don't need to escape " in a regexp.

Upvotes: 3

Related Questions