Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Everything between 2 strings -- Sed

Tags:

grep

shell

sed

awk

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.

like image 697
Anand Abhay Avatar asked Dec 05 '22 08:12

Anand Abhay


2 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)

like image 76
jared_mamrot Avatar answered Dec 14 '22 23:12

jared_mamrot


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
like image 35
RavinderSingh13 Avatar answered Dec 15 '22 00:12

RavinderSingh13