我的文件中有内容:
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
我已经用下面的方法完成了
方法一:
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