add proper error handling for all final exec calls
[hband-tools.git] / user-tools / inisort
blobe2359db630df1ae75e30aa43577b794059f8fe4b
1 #!/usr/bin/env perl
3 use Fcntl;
4 use Data::Dumper;
5 $re_sect_pre = '^(?:\xEF\xBB\xBF|\xFE\xFF)?\s*\[';
6 $re_sect_post = '\]';
7 $re_sect = $re_sect_pre . '(.+?)' . $re_sect_post;
8 $re_key_pre = '^\s*';
9 $re_key_post = '\s*=';
10 $re_key = $re_key_pre . '(.+?)' . $re_key_post;
11 $re_comment = '^\s*[\x23;]';
14 sub seek_to_section
16 my ($sect) = @_;
17 seek $srt_hnd, 0, Fcntl::SEEK_SET;
18 while(<$srt_hnd>)
20 if(/$re_sect_pre\Q$sect\E$re_sect_post/)
22 $section_offset = tell $srt_hnd;
23 return $_;
26 return undef;
29 sub keys_left
31 my ($offset) = @_;
32 seek $srt_hnd, $offset, Fcntl::SEEK_SET;
33 while(<$srt_hnd>)
35 if(/$re_sect/)
37 last;
39 elsif(/$re_key/)
41 my $key = $1;
42 if(not grep {$key eq $_} @ref_keys)
44 print;
52 ($srt_file, $ref_file) = @ARGV;
53 open $srt_hnd, '<', $srt_file or die "$srt_file: $!\n";
54 open $ref_hnd, '<', $ref_file or die "$ref_file: $!\n";
57 while(<$ref_hnd>)
59 if(/$re_sect/)
61 $old_section = $section;
62 $section = $1;
63 if(defined $old_section)
65 keys_left($section_offset);
66 @ref_keys = ();
69 push @ref_sections, $section;
70 undef $section_offset;
71 $section_header = seek_to_section($section);
72 if($section_header)
74 print $section_header;
77 elsif(defined $section_header)
79 if(/$re_comment/)
81 next;
83 elsif(/$re_key/)
85 $key = $1;
86 push @ref_keys, $key;
87 seek $srt_hnd, $section_offset, Fcntl::SEEK_SET;
88 while(<$srt_hnd>)
90 if(/$re_key_pre\Q$key\E$re_key_post/)
92 print;
93 last;
100 if(defined $section_offset)
102 keys_left($section_offset);
104 # sections_left:
105 seek $srt_hnd, 0, Fcntl::SEEK_SET;
106 $do_print = 0;
107 while(<$srt_hnd>)
109 if(/$re_sect/)
111 $sect = $1;
112 $do_print = not grep {$sect eq $_} @ref_sections;
114 if($do_print)
116 print;
121 __END__
123 =pod
125 =head1 NAME
127 inisort - Sort keys in an INI file according to the order of keys in an other INI file
129 =head1 SYNOPSIS
131 inisort [<B<UNSORTED>>] [<B<REFERENCE>>] > [<B<SORTED>>]
133 =cut