1

I have content in my file :

123456789

My output is: 1234CC789

Desired Output is:

1234CC56789

I am insert PP at nth position suppose.

But when I am inserting any text it is inserting the text at that position but also deleting the already present characters.

Please tell me what is wrong.

#!/usr/bin/perl
my $file;
my $char='CC';
my $pos=5;
open($file,'+<',"file.txt") or die $!;
seek($file,$pos,0);
print $file $char;
close($file);
  • Any module which I need to add or is it inbuilt? – Coolstrike Jun 30 at 6:36
  • My examples use only inbuilt. I used not the #! - line, so I have to use "perl perlfile" to call it, but nothing is left out. Perl is ideal for these things. You shloud maybe look for examples of perl scripts to get an idea how to use it. The usual approach is linewise, but the way you started out is also possible. Somewhere the manual speaks of "SLURPING IN" a whole file at once. – user359065 Jul 1 at 12:01
0

You can go about performing the insertion of the string in the middle of the file by means of a judicious mix of seek and read, as shown:

$ perl -wMstrict -e '
   my $if = shift;
   my($str, $ins_pos) = qw/CC 5/;
   my($buffer_pre, $buffer_post);

   open my $fh, "+<", $if
      or die "Opening: $!\n";

   # park the pos pointer at the beginning of file
   seek $fh, 0, 0 or die "Seeking: $!\n";
   my $buffer_pre_size = $ins_pos - 1;
   read($fh, $buffer_pre, $buffer_pre_size) == $buffer_pre_size
      or die "Reading: $!\n";

   # park the pos pointer at the eof
   seek $fh, 0, 2 or die "Seeking: $!\n";
   my $eof_pos = tell $fh;
   my $buffer_post_size = $eof_pos - $ins_pos + 1;

   # park the pos pointer at the insertion location
   seek $fh, $ins_pos-1, 0 or die "Seeking: $!\n";
   read($fh, $buffer_post, $buffer_post_size) == $buffer_post_size
      or die "Reading: $!\n";

   # park the pos pointer at the beginning of file
   seek $fh, 0, 0 or die "Seeking: $!\n";
   print $fh $buffer_pre, $str, $buffer_post;

   close $fh or die "Closing: $!\n";
' file.txt

Results:

1234CC56789
0

You can simplify matters quite a bit by resorting to the dd command. Do a man dd for more details.

{
    dd if=file.txt ibs=4 count=1;
    printf '%s' CC;
    dd if=file.txt ibs=4 skip=1;
} 2>/dev/null

Results:

1234CC56789
-1

I have done in below methods

method1:

echo "123456789"| perl -pne "s//\n/g"| sed '/^$/d'| sed '5i CC'| perl -pne "s/\n//g"

output

1234CC56789

Method2

echo "123456789"| awk -F "" '{$5=$5"CC";print $0}'| sed -r "s/\s+//g"

output

12345CC6789

Method2

echo "123456789"| awk -F "" '{$5=$5"CC";print $0}'| sed -r "s/\s+//g"

output

12345CC6789

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.