-2

I want to insert line beetwen line 2 and line 3 that contain concatenate string from this lines

abc
abcd:
abc
abcd

Output:

abc
abcd:
abcd: abcd
abc
abcd
Axeman
  • 29,660
  • 2
  • 47
  • 102

3 Answers3

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

Dan
  • 10,531
  • 2
  • 36
  • 55
1

Since you don't specify what you want to put after each line that ends with a colon, I've created a table to stand for some generic decision-making and somewhat flexible handling.

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

"Inserting" a line after the current one is as easy as appending that text to the current one and outputting it.

Axeman
  • 29,660
  • 2
  • 47
  • 102
1
perl -p -i.bck -e "if ($last ne ''){ $_=~s/.*/$last $&\\n$&/; $last=''} elsif (/:/) {$last = $_;chomp($last);} else {$last = '';}" test

test is the file in question

Nikodemus RIP
  • 1,369
  • 13
  • 20
  • Running that one-liner, I get errors `syntax error at -e line 1, near "( ne" syntax error at -e line 1, near ";}"` – mrk Nov 14 '12 at 15:55