First, this solution is a simple hack and most likely not the most efficient.
Second, it makes some assumptions about what you mean by
"in the same format as the original", namely that:
1) you want to retain the blank values in the original file even if the corresponding column in the replacement file is not blank.
2) you do not skip the value in the replacement column if the corresponding value in the original file is blank.
( are we confused yet :) )
given the following original file:
1:2:3:4
5:6:7:8
:9:10:11
12:13:14:15
:17:18:19
and the following replacement file:
a:b:c:d:e
f:g:h:i:j
k:l:m:n:o
p:q:r:s:t
u:v:w:x:y
The following code replace the first column (for simplicity sake) in the original file with the first column in the replacement file (according to the assumptions about your requirements I made above).
use File::Copy;
use strict;
my (@col, $val, $i);
open(COL, "<replace.txt");
while(<COL>) {
push @col, $_ =~ m/(.*?):/;
}
close(COL);
open(OUT, ">out.txt");
open(COL, "<original.txt");
while(<COL>) {
($val) = $_ =~ m/(.*?):/;
$_ =~ s/(.*?)(?=:)/$col[$i++]/ unless $val =~ m/^\s*$/;
print OUT $_;
}
close(COL);
close(OUT);
copy("out.txt", "original.txt");
contents of orginal file after program is run:
a:2:3:4
f:6:7:8
:9:10:11
k:13:14:15
:17:18:19
Again, this may or may not be what you want since you were not specific in the meaning of
"in the same format as the original".
davidj
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.