Perl: 파일의 n번째 위치에 삽입

Perl: 파일의 n번째 위치에 삽입

내 파일의 내용은 다음과 같습니다.

123456789

내 결과는 다음과 같습니다 1234CC789

원하는 출력은 다음과 같습니다.

1234CC56789

n번째 위치에 PP를 삽입한다고 가정해 보겠습니다.

그러나 텍스트를 삽입하면 해당 위치에 텍스트가 삽입되지만 기존 문자도 삭제됩니다.

무엇이 문제인지 알려주세요.

#!/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);

답변1

seek다음과 같이 합계를 신중하게 결합하여 파일 중간에 문자열을 삽입할 수 있습니다 read.

$ 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

결과:

1234CC56789

답변2

명령을 사용하면 문제를 크게 단순화할 수 있습니다 dd. 자세한 내용을 보려면 하나를 만드세요 man dd.

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

결과:

1234CC56789

답변3

나는 다음 방법을 사용하여 그것을했다

방법 1:

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

산출

1234CC56789

방법 2

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

산출

12345CC6789

방법 2

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

산출

12345CC6789

관련 정보