[SATLUG] Shell scripting challenge

Sean I siffland at nerdshack.com
Tue Apr 7 20:22:25 CDT 2009


On Sun, Apr 5, 2009 at 11:26 PM, Emon <emon at lavabit.com> wrote:
> Hi all
>
> I am studying for RHCE exam. The instructor is a friend of mine, and he
> has issued me an off topic challenge. The challenge is …....
>
> To write a shell script that will take a given text file as input &
> divide into five equal but different files. If the number of lines in
> the file is not perfectly divisible by five, then  the last file should
> contain the extra lines; i.e. if the total number of lines in the
> original file is 16, then it should divide them into 5 files, where the
> first 4 files should contain 3 lines each & the fifth file should
> contain 4 lines.
>
> I have some very basic (Bash) shell scripting & (C++) programming
> concept, but shamefully I must admit that I can't figure out very much.
>
> All I have figured out is that I should use "wc -l" command to find out
> the number of lines in the file & store it in a variable & then divide
> it by 5; but after that how should I store the quotient & the
> reminder??..... and how do I use those numbers to process the file???
>
> Any help/pointer would be very much appreciated.
>
> Emon
>

Yeah it is not shell, sue me...

#!/usr/bin/perl

use strict;
use warnings;

use File::Path;

my $begin = () ;
my $count = () ;
my $end = () ;
my $file = '/tmp/file' ;
my @hosts = () ;

open(FILE, "< $file") or die ("can't open $file: $!");
$count++ while <FILE>;

open(FILE, "< $file") or die ("can't open $file: $!");
@hosts=<FILE>;

my $dividend = $count ;
my $divisor = 5 ;
my $quotient = ($dividend - ($dividend % $divisor)) / $divisor ;
my $remainder = $dividend % $divisor ;

$begin = 0;
$end = ($quotient - 1);

for (my $number = 1; $number <= 4; $number++) {

  open DAT, ">>/tmp/test$number" or die $!;
  print DAT @hosts[$begin..$end];
  $begin = ($end + 1);
  $end = ($begin + $quotient -1);
  close DAT;
}

$end = ($end + $remainder);
open DAT, ">>/tmp/test5" or die $!;
print DAT @hosts[$begin..$end];
close DAT;


kinda ugly, but it works on most platforms.....


More information about the SATLUG mailing list