Find Everything between 2 strings -- Sed

Viewed 96

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.

3 Answers

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)

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

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

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