Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Treating the last line differently 1

Status
Not open for further replies.

columb

IS-IT--Management
Feb 5, 2004
1,231
0
0
EU
I have a perl script I would like to migrate to awk. It's quite simple - it copies a file and amends the footer to reflect the number of records (line count so far minus one for the header). In perl it looks like
Code:
#!/usr/bin/perl -w
use strict;

$#ARGV == 2 or die "Invalid agument count\n";
open IFH, $ARGV[0] or die "Unable to open $ARGV[0] for reading\n";
open OFH, ">$ARGV[1]" or die "Unable to open $ARGV[1] for writing\n";
open UFH, ">$ARGV[2]" or die "Unable to open $ARGV[2] for writing\n";

my $count = -1;
while (<IFH>)
  {
  eof ( IFH ) or $count++,(print OFH), next;
  my @bits = split /\|/;
  $bits[1] = sprintf "%9.9d", $count;
  print OFH +(join '|', @bits), "\n";
  printf UFH "%9.9d\n", $count;
  }
close IFH;
close OFH;
close UFH;
I'm not looking for a full solution but I'd like some hints on how to identify the last line so as to treat it differently.

Thanks


On the internet no one knows you're a dog

Columb Healy
 
Hi

Sorry, I have no idea how to explain it, so here is a possible way.
Code:
#!/usr/bin/awk -f

BEGIN {
  FS=OFS="|"

  if (ARGC!=4) { print "Invalid agument count"; exit }

  i=-1
  while (getline < ARGV[1]) {
    if (i++!=-1) print prev > ARGV[2]
    prev=$0
  }

  $1=sprintf("%9.9d",i)
  print > ARGV[2]

  printf "%9.9d\n",i > ARGV[3]

  close(ARGV[1])
  close(ARGV[2])
  close(ARGV[3])
}
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].

Feherke.
 
Gotcha -

It's sort of
First line - store in prev
Subsequent lines - print prev then store new line in prev - i.e. print the line before.
When completed print reformatted final line

Thanks Feherke - you're a star as ever.



On the internet no one knows you're a dog

Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top