Reputation: 649
I have a input file which has large data in below pattern. some part of data is shown below:
Data1
C
In;
CP
In;
D
In;
Q
Out;
Data2
CP
In;
D
In;
Q
Out;
Data3
CP
In;
CPN
In;
D
In;
QN
Out;
I want my output as
Data1(C,CP,D,Q)
In C;
In CP;
In D;
Out Q;
Data2 (CP,D,Q)
In CP;
In D;
Out Q;
Data3 (CP,CPN,D,QN)
In CP;
In CPN
In D
Out QN;
I tried code given in comment section below, But getting error. Corrections are welcome.
Upvotes: 0
Views: 158
Reputation: 1126
and variation on @vgersh99 but setting FS
twice: at the beginning and at the end.
awk -v FS='\n' -v RS= '
{
gsub(";", " ");
r2= $3 $2;
r3= $5 $4;
r4= $7 $6;
}
{print $1}
{print r2 FS}
{print r3 FS}
{print r4 FS}' FS=';' file
Data
In A1;
In A2;
Out Z;
'''
Does it give you error?
Upvotes: 1
Reputation: 945
variation on @EdMorton suggestion - fixing the desired order of fields:
$ awk 'FNR==1{print;next}!(NR%2){a=$0; next} {printf "%s %s%s%s", $1,a,FS,ORS}' FS=';' file
Data
In A1;
In A2;
Out Z;
Upvotes: 3
Reputation: 203219
$ awk 'NR%2{print sep $0; sep=OFS; next} {printf "%s", $0}' file
Data
A1 In;
A2 In;
Z Out;
Upvotes: 2
Reputation: 133438
Could you please try following, written and tested with shown samples.
awk '
FNR==1{
print
next
}
val{
sub(/;$/,OFS val"&")
print
val=""
next
}
{
val=$0
}
END{
if(val!=""){
print val
}
}' Input_file
Issues in OP's attempt:
1st: awk
code should be covered in '
so "$1=="A1"
should be changed to '$1=="A1"
.
2nd: But condition for logic looking wrong to me because if we only looking specifically for A1
and In
then other lines like Z
and out
will miss out, hence came up with above approach.
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
FNR==1{ ##Checking condition if this is first line then do following.
print ##Printing current line here.
next ##next will skip all further statements from here.
}
val{ ##Checking condition if val is NOT NULL then do following.
sub(/;$/,OFS val"&") ##Substituting last semi colon with OFS val and semi colon here.
print ##printing current line here.
val="" ##Nullify val here.
next ##next will skip all further statements from here.
}
{
val=$0 ##Setting current line value to val here.
}
END{ ##Starting END block of this program from here.
if(val!=""){ ##Checking condition if val is NOT NULL then do following.
print val ##Printing val here.
}
}' Input_file ##Mentioning Input_file name here.
Upvotes: 1