perl在文本中找到aaa在哪一行,并在这一行上面添加10行文字
时间: 2024-02-06 10:09:27 浏览: 112
可以使用Perl的文件操作和文本操作模块来实现这个功能。具体实现如下:
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'example.txt'; # 文件名
my $search_str = 'aaa'; # 要查找的字符串
my $num_lines = 10; # 要添加的行数
open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";
my $line_num = 0;
while (my $line = <$fh>) {
$line_num++;
if ($line =~ /$search_str/) {
# 找到了要查找的字符串,添加指定行数的文本
for (my $i=1; $i<=$num_lines; $i++) {
print "Added line $i above line $line_num\n";
print "This is line $i\n";
}
}
print $line;
}
close($fh);
这个脚本会打开指定的文件,逐行读取文件内容并查找是否包含指定的字符串。如果找到了要查找的字符串,脚本会在该行上面添加指定行数的文本。
你需要将 $filename
替换为你的文本文件名,将 $search_str
替换为你要查找的字符串,将 $num_lines
替换为你需要添加的行数。运行脚本后,它会输出修改后的文本到标准输出。如果你需要将修改后的文本写回到文件中,可以使用Perl的文件写操作模块来实现。
相关推荐


















