Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 394
  • Last Modified:

Perl - Replacing a record at a specific position

Hi,

Using Perl, how could you replace a record at a specific position of a fixed length file?    Also, need to do multiple replacement at different positions for the same record.

For example, the file contains the following record:

-->  Need to change THIS first then THIS second ...<rest of line, 700 chars total>

Note:  1st "THIS" is at positions 16-19 and 2nd "THIS" is at position 32-35.

Goal:

Replace position 16 to 19 (len = 4), "THIS", with "XXXX"
and
Replace position 32 to 35 (len = 4), "THIS", with "YYY" << len different

Results:

--> Need to change XXXX first then YYYS second ...<rest of line, 700 chars total>

Note:  The 2nd replacement replaced "THIS" with "YYYS"; 'S' was kept and the records length was not changed, contained 700 chars (same as original)

Thank you



 
I need to change several
I need to modify a fixed length file, at several positions o
0
tkir
Asked:
tkir
3 Solutions
 
ozoCommented:
open F,"+<file" or die $!;
seek F,15,0;
print F "XXXX";
seek F,31,0;
print F "YYY";
close F;
0
 
DaemonBarberCommented:
try something like:


while(<STDIN>)
  {
  my($line) = $_;
  chomp($line);
  substr($line, 16, 4) = "XXXX";
  substr($line, 32, 3) = "YYY";
  print "$line\n";
  }
0
 
namethisCommented:
In this case, there is no more magic in Perl than in any other language.
While files are not too big, just read a file, change data, and write it back:
@subs=([19,4,'XXXX'], [32,4,'YYY']);
open F, '<+:raw', $file or die$!;
read F, $data, -s F;
for $sub(@subs)  {
   substr($data, $sub->[0],$sub->[1])=$sub->[2];
}
open F, '>:raw', $file or die$!; 
print F $data;

Open in new window

Otherwise, you'll need to read the file piece-meal and write changed data into another file.
Of course, if replaced and replacing data have the same length, you can change the file
in place (see the first answer by ozo).
0
 
tkirAuthor Commented:
Thank you!!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now