?
Solved

Insert a line in an order TEXT file

Posted on 1998-07-22
5
Medium Priority
?
237 Views
Last Modified: 2010-03-04
Hi,

I would like to know if they have a way to insert a line in
an order TEXT file
example :
Line to insert = "HAA|123"

TEXT file:
AAA|111
BBB|222
>> insert here HAA|123 by looking the 3 first characters
NAA|555
PPP|666
QQQ|777
0
Comment
Question by:woaini
  • 2
  • 2
5 Comments
 
LVL 5

Accepted Solution

by:
b2pi earned 200 total points
ID: 1208623
use strict;

open(SRC, "<orig.file.name") || die "Couldn't open source";
open(DST, ">orig.file.name.TMP") || die "Couldn't open destination";

my($target) = $ARGV[1]; ## The first parameter is the line to insert
while (<SRC>) {
   chomp;
   if ($target le $_) {
      print DST "$target\n";
      print DST "$_\n";
     while (<SRC>) {
         print DST $_;
    }
   print "$_\n";
}
close(SRC);
close(DST);
unlink ("orig.file.name");
rename("orig.file.name.TMP", "orig.file.name");


0
 
LVL 85

Expert Comment

by:ozo
ID: 1208624
#or
$target = (shift)."\n";
{local $^I = ".TMP"; local @ARGV=("orig.file.name");
 while( <> ){
   print $target if substr($target,0,3) le substr($_,0,3) && ??;
   print;
 }
}
0
 
LVL 85

Expert Comment

by:ozo
ID: 1208625
Oops, that doesn't work if $target comes after all the lines in orig.file.name
(actually, neither does the original answer,
but b2pi's version is easier to fix)
0
 
LVL 5

Expert Comment

by:b2pi
ID: 1208626
Good point, Ozo.

Add to above: (directly before
close(SRC);

the following:

print "$target\n" if $target gt $_;
close(SRC);
etc...


0
 

Author Comment

by:woaini
ID: 1208627
Thank a lot b2pi !!
Thank ozo too.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question