Sharanabasu Angadi
Sharanabasu Angadi

Reputation: 4372

shell script to get key value

I have content like

key1="value1" key2="value2"
key1="value11" key2="value22"
key1="value111" key2="value222"

I want to output like

value1
value11
value111

i.e basically values for key one

but when I grep the entire line will be shown, I tried using cut still could not get expected result, can some help me to write scrip for this please

Upvotes: 1

Views: 2250

Answers (3)

anishsane
anishsane

Reputation: 20980

Using grep -P:

$ grep -oP '(?<=key1=")[^"]*' file
value1
value11
value111

Upvotes: 1

anubhava
anubhava

Reputation: 785098

Using awk you can search for given key like this:

awk -v s="key1" -F '[= "]+' '{for (i=1; i<NF; i+=2) if ($i==s) print $(i+1)}' file
value1
value11
value111

awk -v s="key2" -F '[= "]+' '{for (i=1; i<NF; i+=2) if ($i==s) print $(i+1)}' file
value2
value22
value222

Upvotes: 2

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

Using cut itself:

cut -d \" -f 2 < File

Set " as delimiter and extract the 2nd field. Hope it helps.

Another similar solution with awk:

awk -F\" '{print $2}' File

Upvotes: 1

Related Questions