我想插入 line beetwen line 2 和 line 3 包含来自此行的连接字符串
abc
abcd:
abc
abcd
输出:
abc
abcd:
abcd: abcd
abc
abcd
我想插入 line beetwen line 2 和 line 3 包含来自此行的连接字符串
abc
abcd:
abc
abcd
输出:
abc
abcd:
abcd: abcd
abc
abcd
You want to add something after a line that ends with a colon, or after line 2?
If after line 2, you can split("\n", $string)
to get an array of lines, splice the new line into the array in position 2, and then join("\n", @array)
to get the string back.
If after the line ending in the colon, you can use a regex: s/(:\n)/\1YOUR_NEW_LINE_HERE\n/
.
由于您没有指定要在以冒号结尾的每一行之后放置的内容,因此我创建了一个表格来代表一些通用决策和一些灵活的处理。
# create a table
my %insert_after
= ( abcd => "abcd: abcd\n"
, defg => "defg: hijk\n"
);
# create a list of keys longest first, and then lexicographic
my $regs
= '^('
. join( '|', sort { length $b <=> length $a or $a cmp $b }
keys %insert_after
)
. '):$'
;
my $regex = qr/$regs/;
# process lines.
while ( <> ) {
m/$regex/ and $_ .= $insert_after{ $1 } // '';
print;
}
在当前行之后“插入”一行就像将该文本附加到当前行并输出一样简单。
perl -p -i.bck -e "if ($last ne ''){ $_=~s/.*/$last $&\\n$&/; $last=''} elsif (/:/) {$last = $_;chomp($last);} else {$last = '';}" test
test 是有问题的文件