Anand Abhay
Anand Abhay

Reputation: 359

Find Everything between 2 strings -- Sed

I have file which has data in below format.

{"default":true,"groupADG":["ABC","XYZ:mno"],"groupAPR":true}
{"default":true,"groupADG":["PQR"],"groupAPR":true} 

I am trying to get output as

"ABC","XYZ:mno"
"PQR"

I tried doing it using sed but somewhere I am going wrong .

 sed -e 's/groupADG":[\(.*\)],"groupAPR"/\1/    file.txt

Regards.

Note: If anyone is rating the question negative, I would request to give a reason also for same. As I have tried to fix it myself , since I was unable to do it I posted it here. I also gave my trial example.

Upvotes: 5

Views: 117

Answers (3)

Carlos Pascual
Carlos Pascual

Reputation: 1126

With awk setting FS as [][] and the condition /groupADG/

awk -F'[][]' '/groupADG/ {print $2}' file
"ABC","XYZ:mno"
"PQR"

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133528

With your shown samples, following may also help you on same.

awk 'match($0,/\[[^]]*/){print substr($0,RSTART+1,RLENGTH-1)}' Input_file

OR with OP's attempts try with /"groupADG" also:

awk 'match($0,/"groupADG":\[[^]]*/){print substr($0,RSTART+12,RLENGTH-12)}' Input_file

Upvotes: 4

jared_mamrot
jared_mamrot

Reputation: 26630

Here is one potential solution:

sed -n 's/.*\([[].*[]]\).*/\1/p' file.txt

To exclude the brackets:

sed -n 's/.*\([[]\)\(.*\)\([]]\).*/\2/p'

Also, this would work using AWK:

awk -F'[][]' '{print $2}' file.txt

Just watch out for edge cases (e.g. if there are multiple fields with square brackets in the same line you may need a different strategy)

Upvotes: 9

Related Questions