made csv2sql mig aware
[migration-tools.git] / text / join_lines
1 #!/usr/bin/perl -w
2 ###############################################################################
3 =pod
4
5 =head1 NAME
6
7 join_lines - program for joining adjacent lines from stdin or one or more files
8
9 =head1 SYNOPSIS
10
11 B<join_lines> [options...] [text files...]
12
13 =head1 DESCRIPTION
14
15 B<join_lines> is used to join adjacent lines from stdin or one or more files,
16 trimming trailing line feeds and carriage returns, and sending the output to
17 stdout. Arguments are used to define the criteria and exact behavior.
18
19 =head1 OVERVIEW
20
21 B<join_lines> understands the following optional arguments:
22
23 =over 15
24
25 =item --help
26
27 Show this documentation.
28
29 =item --delimiter=<d>
30
31 B<join_lines> will use the specified delimiter <d> to separate joined lines. The
32 default is to use no delmiter when joining lines.
33
34 =item --lines=<n>
35
36 This will cause B<join_lines> to join every <n> lines into one line.
37
38 =item --record-separator=<s>
39
40 This will cause B<join_lines> to immediately start a new line when it encounters
41 a line solely containing <s>. That line itself will not otherwise be used. This
42 argument may be used in conjunction with --lines, but probably should not be. :)
43
44 =item --record-separator-empty-line
45
46 This works like --record-separator, but is a way to define an "empty" line as
47 being the record separator.
48
49 =back
50
51 =cut
52 ###############################################################################
53
54 use strict;
55 use Pod::Usage;
56 use Getopt::Long;
57
58 my $help;
59 my $delimiter;
60 my $linecount;
61 my $record_separator;
62 my $record_separator_empty_line;
63
64 GetOptions(
65         'delimiter=s' => \$delimiter,
66         'lines=s' => \$linecount,
67         'record-separator=s' => \$record_separator,
68         'record-separator-empty-line' => \$record_separator_empty_line,
69         'help|?' => \$help
70 );
71 pod2usage(-verbose => 2) if $help; 
72
73 my $count = 0;
74 my @lines = ();
75
76 sub join_lines {
77     print join($delimiter || '', @lines) . "\n";
78     @lines = ();
79     $count = 0;
80 }
81
82 while (my $line = <>) {
83     $count++;
84     $line =~ s/[\r\n]+$//g;
85     if (defined $record_separator_empty_line && $line eq '') {
86         join_lines();
87     } elsif (defined $record_separator && $line eq $record_separator) {
88         join_lines();
89     } elsif (defined $linecount && $count == $linecount) {
90         push @lines, $line;
91         join_lines();
92     } elsif (! defined $linecount && ! defined $record_separator && ! defined $record_separator_empty_line) {
93         print "$line\n"; # passthru when given no arguments
94     } else {
95         push @lines, $line;
96     }
97 }
98 if (scalar(@lines) > 0) {
99     print join($delimiter || '', @lines) . "\n";
100 }