Issue
file has:
@xyz, xyz, (z){.class1 .classA,.class2,.class3,.class4 .classB{background-image:url("1.png")}}
.classA,.classB .class1{color:blue}
expected:
@xyz, xyz, (z){.class1 .classA{background-image:url("1.png")}}
@xyz, xyz, (z){.class2{background-image:url("1.png")}}
@xyz, xyz, (z){.class3{background-image:url("1.png")}}
@xyz, xyz, (z){.class4 .classB{background-image:url("1.png")}}
.classA{color:blue}
.classB .class1{color:blue}
How to ungroup?
awk '{count=gsub(/,\./, ",."); if ($0 ~ /,./) for(i=0;i<=count;i++) print $0; if ($0 !~ /,./) print $0 }'
gives:
@xyz, xyz, (z){.class1 .classA,.class2,.class3,.class4 .classB{background-image:url("1.png")}}
@xyz, xyz, (z){.class1 .classA,.class2,.class3,.class4 .classB{background-image:url("1.png")}}
@xyz, xyz, (z){.class1 .classA,.class2,.class3,.class4 .classB{background-image:url("1.png")}}
@xyz, xyz, (z){.class1 .classA,.class2,.class3,.class4 .classB{background-image:url("1.png")}}
.classA,.classB .class1{color:blue}
.classA,.classB .class1{color:blue}
Solution
1st solution(GNU awk
): With your shown samples please try following GNU awk
code. Written and tested in GNU awk
. This code validates the number of opening and closing {
and }
but again it checks only number of them and its not intelligent to tell you that its a valid CSS or not that a css parser could only do.
awk '
gsub(/{/,"&")==1 && gsub(/}/,"&")==1 && match($0,/(^[^{]*){(.*)}$/,arr1){
num=split(arr1[1],arr2,",")
for(i=1;i<=num;i++){
print arr2[i]"{"arr1[2]"}"
}
next
}
gsub(/{/,"&")==gsub(/}/,"&") && gsub(/{/,"&")>1 && match($0,/(^.*){(.*)}}$/,arr3){
split(arr3[1],arr4,"{")
num1=split(arr4[2],arr5,",")
for(i=1;i<=num1;i++){
print arr4[1]"{"arr5[i]"{"arr3[2]"}}"
}
}
' Input_file
2nd solution: This should work in any POSIX awk
. Written and tested with shown samples Only.
awk '
gsub(/{/,"&")==1 && gsub(/}/,"&")==1{
split($0,arr1,"[}{]")
num1=split(arr1[1],arr2,",")
for(i=1;i<=num1;i++){
print arr2[i]"{"arr1[2]"}"
}
next
}
gsub(/{/,"&")==gsub(/}/,"&") && gsub(/{/,"&")>1{
num2=split($0,arr3,"{")
num3=split(arr3[2],arr4,",")
for(i=1;i<=num3;i++){
print arr3[1]"{"arr4[i]"{"arr3[num2]
}
}
' Input_file
With your shown samples output will be as follows:
@xyz, xyz, (z){.class1 .classA{background-image:url("1.png")}}
@xyz, xyz, (z){.class2{background-image:url("1.png")}}
@xyz, xyz, (z){.class3{background-image:url("1.png")}}
@xyz, xyz, (z){.class4 .classB{background-image:url("1.png")}}
.classA{color:blue}
.classB .class1{color:blue}
Answered By - RavinderSingh13 Answer Checked By - Dawn Plyler (WPSolving Volunteer)