Hi tyler,
Thanks a lot for your reply. It is working fine, but my requirement is something different.
test.txt file:
-------------
[inmis@inapp cdr_kallol]$ cat test.txt
header
{
subheader1
{
field1 : value
field2 : value
field3: value
}
subheader2
{
subheader3
{
field4 : value
field5 : value
field6: value
}
subheader4
{
field7 : value
field8 : value
field9: value
}
}
}
header
{
subheader1
{
field1 : value1
field2 : value1
field3: value1
}
subheader2
{
subheader3
{
field4 : value1
field5 : value1
field6: value1
}
subheader4
{
field7 : value1
field8 : value1
field9: value1
}
}
}
[inmis@inapp cdr_kallol]$ perl -ne 'BEGIN {$i=0} chomp;
if(/{/) {$i++}
elsif(/:/) {split/[: ]+/;push @x,$_[0];push @y,$_[1]}
elsif(/}/) {$i--;
if($i == 0) {
printf("%s\n%s\n",join(",",@x),join(",",@y));
@x=(); @y=()
}}' test.txt
field1,field2,field3,field4,field5,field6,field7,field8,field9
value,value,value,value,value,value,value,value,value
field1,field2,field3,field4,field5,field6,field7,field8,field9
value1,value1,value1,value1,value1,value1,value1,value1,value1
But the requirement is :
field1,field2,field3,field4,field5,field6,field7,field8,field9
value,value,value,value,value,value,value,value,value
value1,value1,value1,value1,value1,value1,value1,value1,value1
.......
There may be n numbers of data and I require in this format.
I have tried some different way..
Can you please look into it?
use IO::File;
open (INPUT_FILE, $ARGV[0]) || die "cant open file\n";
my @body = <INPUT_FILE>;
my $count= 0;
$no_of_lines=scalar(@body);
for ( $i = 0 ; $i < $no_of_lines ; $i++)
{
$variable = $body[$i];
if ( $variable =~ "field1")
{
@tmp_var = split(/([:\'])/,$variable);
$field1 = $tmp_var[4];
print "$field1,";
}
if ( $variable =~ "field2")
{
@tmp_var = split(/([:\'])/,$variable);
$field2 = $tmp_var[4];
print "$field2,";
}
if ( $variable =~ "field2")
{
@tmp_var = split(/([:\'])/,$variable);
$field2 = $tmp_var[4];
print "$field2,";
}
...
...
}
print "\n";
It is a very bad way I have written, but main problem is that I can not write any else in the loop. I have to track whether any field1 or field2 is missing.
The logic is :
1. Match -> field1:value1
2. If field1 exists then print value1
3. else
4. print null
Then the output will come
field1,field2,field3,field4,field5,field6,field7,field8,field9
value,value,value,,value,value,value,value,value
value1,value1,value1,value1,value1,value1,,value1,value1
In the above output first line field4 is missing
and in the second line field7 is missing
Can you please help here ? ....
Regards
---------- Post updated at 06:56 AM ---------- Previous update was at 06:52 AM ----------
In the Code I have written
$field1 = $tmp_var[4];
actually original data written in this format
field1 : 'value1'
One single cote is there