Perl: Вставка в n-ю позицию в файле

La extensión es para evitar conflictos con la multitud de renamecomandos disponibles en Debian. Este cambio se realizó en 2007 en respuesta al error de Debian #439647:

/usr/bin/rename is managed by the alternatives system (with Perl's version the default). util-linux 2.13~rc3-8 installs its own binary there, instead of registering it as an alternative.

En respuesta,util-linuxrenamepasó a llamarse rename.ul.

Aun así, rename.ulla sintaxis es tan diferente de las variantes de Perl que no se agrega al sistema alternativo de forma predeterminada (consulte Debian bug #439935).

1
28.06.2019, 14:06
3 ответа

Вы можете вставить строку в середину файла с помощью разумного сочетания 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
0
28.01.2020, 02:11

Вы можете немного упростить ситуацию, воспользовавшись командой 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
0
28.01.2020, 02:11

Я сделал описанными ниже методами

метод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
-1
28.01.2020, 02:11

Теги

Похожие вопросы