foreach my $line (<$infh>) { if ($line =~ /$re_data/) { # Split on whitespace, surround with parens, join with commas push @data, "(" . join(",", split(/\s+/, $line)) . ")"; } } #### # Simply 'join' all data; last record contains neither comma nor newline. my $data = join(",\n", @data); #### #!/usr/bin/perl use strict; use warnings; use feature qw( say ); use IO::File; ################## ## User-defined ## ################## my $input = 'in.txt'; # Input file my $output = 'out.txt'; # Output file my $re_data = qr/^[0-9]+/; # Detect lines containing records ################## ## Main program ## ################## # Read the input my $infh = IO::File->new($input) or die "Can't read '$input' ($!)"; my @data = ( ); foreach my $line (<$infh>) { if ($line =~ /$re_data/) { # Split on whitespace, surround with parens, join with commas push @data, "(" . join(",", split(/\s+/, $line)) . ")"; } } close($infh); # Simply 'join' all data; last record contains neither comma nor newline. my $data = join(",\n", @data); # Create the output my $text = qq{ SELECT CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION FROM DB.CUSTOMER_DATA WHERE (CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION) IN ( $data ) }; $text =~ s/\n\s+/\n/g; # Remove indentation (for "looks") # Write the output my $outfh = IO::File->new; open($outfh, '>', $output) or die "Can't write '$output' ($!)"; print $outfh $text; close($outfh); say "Wrote '$output'"; #### SELECT CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION FROM DB.CUSTOMER_DATA WHERE (CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION) IN ( (0001,20000001,john,CA), (0002,30000002,neill,WI), (0003,40000003,joe,GA), (0004,50000004,will,IL), (0005,60000005,mike,IN), (0006,70000006,bill,AK) )