Click to See Complete Forum and Search --> : Add new fields to FFDB
edatz
12-30-2011, 02:25 PM
I have a bunch of old Flat File Databases that I have merged into one file.
What I need to do now is add an ID at the beginning and new fields at the end of each record.
AAA|aaa
BBB|bbb
CCC|ccc
DDD|ddd
So that I have
1|AAA|aaa|0|||||
2|BBB|bbb|0|||||
3|CCC|ccc|0|||||
4|DDD|ddd|0|||||
Is there a quick to do this?
Doesn't have to be fancy or "perfect" Perl.
Hope someone can help, thanks.
Sixtease
12-31-2011, 02:44 AM
my @new_fields = (0, '', '', '', '', '');
while (<>) {
print join('|', $., $_, @new_fields);
}
edatz
12-31-2011, 02:53 AM
Hi Sixtease, Happy New Year to you.
I just managed to do the end fields before I saw your post.
All that's left is the new first field for the ID numbers. I'm guessing that I would have to do some kind of loop that starts at 1 and adds 1 for each record.
Oh yeah, I forgot to say this is Perl.
Update:
I have a new empty first field so this is the current record state
|AAA|aaa|0|||||
|BBB|bbb|0|||||
|CCC|ccc|0|||||
|DDD|ddd|0|||||
I am trying, but not a numbers person. Would I start with something like this?
$numid += 1;
It's how to loop it that I don't understand. I think it would have to be a foreach within a foreach? - don't know.
Cheers - edatz
Sixtease
12-31-2011, 03:42 AM
Just delete the @new_fields from my script above.
edatz
12-31-2011, 04:56 AM
Hi Sixtease, made a mess of things. I should have posted the code that I'm using.
My fault, sorry that I didn't include the code.
This is what I've used (it's just a quick and dirty thing that I'm only ever going to do once, on a file with hundreds of records).
$dbfile = "test.txt";
open (EDBF,"<$dbfile") || die("Cannot open $dbfile");
@dbe=<EDBF>; close (EDBF);
open (EDBF,">$dbfile") || die("Cannot open $dbfile");
chomp;
foreach $rec (@dbe) {
chomp($rec);
$numid += 1; # don't know how to use this - or even if it's right.
@fd=split /\|/, "$rec";
print EDBF "|$fd[0]|$fd[1]|0|||||\n";
}
close (EDBF);
exit;
This has produced a file which reads as
|AAA|aaa|0|||||
|BBB|bbb|0|||||
|CCC|ccc|0|||||
|DDD|ddd|0|||||
Which means each record is now
$fd[0]|$fd[1]|$fd[2]|0|||||
The new first field is the one where I need to put the ID, using the numid variable. I did try, but all it did was put the number 1 in each record.
Hope this makes sense - edatz
Sixtease
12-31-2011, 05:18 AM
Hi. Firstly, yes, your use of $numid seems correct. print EDBF "$numid|$fd[0]|$fd[1]|0|||||\n"; should do the trick. Otherwise, I insist you can use the script I posted above sans the @new_fields variable. Just give it your current file as first argument and it will add the numbers to it, printing them to stdout.
edatz
12-31-2011, 05:45 AM
That did the trick.
I didn't realize it was that easy. Odd, you think something will be really difficult and it isn't or that a process will be very easy and it turns out to seriously complicated. :)
Thank you very much Sixtease.