-2

我想插入 line beetwen line 2 和 line 3 包含来自此行的连接字符串

abc
abcd:
abc
abcd

输出:

abc
abcd:
abcd: abcd
abc
abcd
4

3 回答 3

1

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/.

于 2011-12-12T08:52:53.647 回答
1

由于您没有指定要在以冒号结尾的每一行之后放置的内容,因此我创建了一个表格来代表一些通用决策和一些灵活的处理。

# 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;
}

在当前行之后“插入”一行就像将该文本附加到当前行并输出一样简单。

于 2011-12-12T12:55:48.607 回答
1
perl -p -i.bck -e "if ($last ne ''){ $_=~s/.*/$last $&\\n$&/; $last=''} elsif (/:/) {$last = $_;chomp($last);} else {$last = '';}" test

test 是有问题的文件

于 2011-12-12T13:45:19.867 回答