Alexx
Alexx

Reputation: 475

Perl:How to insert line in a file?

I am reading from two files. I'm trying to insert a line from file2 to file1 whenever column 1 contents matches.

##FILE1

1   wr  5769        78670002    fqefq  
3   wr  5769        78650003    hfhhg  
5   wr  5769        88990001    dfdsv

##FILE2

1   Step1  
3   Step3  
5   Step5

Desired Output:

1   wr  5769        78670002    fqefq  
Step1
3   wr  5769        78650003    hfhhg
Step3  
5   wr  5769        88990001    dfdsv
Step5

Code tried:

my $rk="rk.log";
open(my $tt, "<$rk" ) or die "Could not open file $trk: $!";
    while (<$tt>) {
       if ($_ =~ /^(\d+)\s+wr\s+5769\s+(\w+)\s+\.*/gm) { 
          open(p1,"<$temp1") or die "Could not open file $temp1: $!"; 
              while (my $newl = <p1>) {
                   my @fs1 = split " ", $newl;
                   if ($fs1[0] eq $1){
                      print "@fs1\n";
                      print "step   $2\n";
                      } else {
                      print "@fs1\n";
                   }
             }
        }
  }
close p1;
close $tt;

Above code doesn't giving the desired output. Can anyone suggest me better way to do it?

Update ##FILE2

2   Step1  
4   Step3  
6   Step5

Upvotes: 2

Views: 132

Answers (3)

ssr1012
ssr1012

Reputation: 2589

This is works for me:

use Tie::File;

my $fle1 = $ARGV[0]; my $fle2 = $ARGV[1];

open(FL2, $fle2) || die "Couldn't read file $fle2\: $!\n";
my $flecnt2 = do {  local $/; <FL2>; };
close(FL2);

my @array;
tie @array, 'Tie::File', $fle1 || die "Error: Couldn't read and write \"$fle1\" file: $!";
my $str = join "\n", @array;

$str=~s#^([^\s]+)\s(.+)$# my $fulcnt=$&;

    if($flecnt2=~m/^$1\s+(.+)$/m)
    {
        $fulcnt .= "\n$&";
    }
    ($fulcnt);
    #egm;

@array = split/\n/, $str;
untie @array;

Upvotes: 0

Johnson
Johnson

Reputation: 171

I believe the simplest method would be to import the two files into separate strings, then create a loop which:

  1. Finds match in file 1. (Include line breaks in your matches)
  2. Appends match to third string.
  3. Deletes match from file 1. (Replace with nothing)
  4. Finds match from file 2. (Include line breaks in your matches)
  5. Appends match to third string.
  6. Deletes match from file 2.

This way you will sequentially order all of your matches from the two files into a string that you can export as a file.

Upvotes: 0

Dave Cross
Dave Cross

Reputation: 69314

Hopefully, a bit of pseudocode will be enough to get you on the right track.

  • Read file2 into a hash (where the key is the integer and the value is the whole line)
  • Open file1
  • Read file1 a line at a time
    • Print the line from file1
    • Extract the integer from the start of the line from line1
    • If that integer exists in your hash
      • Print the line from file2

Upvotes: 3

Related Questions