Reputation: 39
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
Upvotes: -2
Views: 1024
Reputation: 1379
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
Upvotes: 1
Reputation: 29854
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.
Upvotes: 1
Reputation: 10786
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/
.
Upvotes: 1