首页 > 解决方案 > use perl to repeat a line fixed no. of times

问题描述

I have a file and i want to repeat some a fixed no. of line below it two times and also to add a loop command just after the second line and end the loop after the second line ends. so my file is

a4 b2 c3 e6
a1 b2 c3 d4
g5 h6 i7 j8
h9 i10 j11 k12

this should become

a4 b2 c3 e6
a1 b2 c3 d4
a1 b2 c3 d4
a1 b2 c3 d4
loop
g5 h6 i7 j8
endloop
h9 i10 j11 k12

I have to do this for 16 files .I am trying to use sed command but it is not working.I am figuring it how to do using perl?

I was trying to use perl -ne 'print $_ x 3' file but it operates on all the lines present in file.

/edit suggested by ikegami/

标签: shellperlscripting

解决方案


perl -wpe'if ($.==2) { $_ x= 3 } elsif ($.==3) { $_ = "loop\n${_}endloop\n" }' <infile >outfile

or to change multiple files in place:

perl -i -wpe'close ARGV if eof; if ($.==2) { $_ x= 3 } elsif ($.==3) { $_ = "loop\n${_}endloop\n" }' file1 file2 file3 

(the close is necessary to restart $.'s line count)


推荐阅读