Inserting a new line into an already existing file

hello ..

I am new to perl scripting, I have a text file, and would like to insert 3 new lines into the same file at different line numbers using perl scripting. Any Help regarding this will be very useful.

say the file is sample.txt, contents are

aaaaa
bbbb
ccccc
dddd
eeeee
ffffffff
ggggg

now i want to insert 3 new lines into the file, it should be as follows

11111
aaaaa
bbbb
ccccc
dddd
eeeee
ffffffff
2222
3333
ggggg

Thanks in advance

Please use code tags for sample data. Try:

perl -pe '$_="11111\n$_" if $.==1;$_.="2222\n3333\n" if $.==6' sample.txt

when i call this command using from a perl script

system(perl -pe '$_="11111\n$_" if $.==1;$_.="2222\n3333\n" if $.==6'sample.txt); 

i am getting the following errors

Number found where operator expected at sample.txt near ""perl -pe '$_="11111"
(Missing operator before 11111?)
Backslash found where operator expected at sample.txt, near "11111\"
        (Missing operator before \?)
String found where operator expected at sample.txt near "$_" if $.==1;$_.=""
        (Missing operator before " if $.==1;$_.="?)
Number found where operator expected at sample.txt near "" if $.==1;$_.="2222"
        (Missing operator before 2222?)
Backslash found where operator expected sample.txt near "2222\"
        (Missing operator before \?)
Backslash found where operator expected at sample.txt, near "n3333\"
syntax error at sample.txt near ""perl -pe '$_="11111"

---------- Post updated at 06:48 PM ---------- Previous update was at 06:22 PM ----------

system("perl -pe '$_="11111\n$_" if $.==1;$_.="2222\n3333\n" if $.==6'sample.txt");

still i am getting the same errors

  1. If you are running a command from perl why don`t you open file directly and do it with perl OPEN function?
  2. while you are running the command you need to escape $ & " in command line, those are intended to be used on command line. When you use the command this way your running program is replacing those values! also ' " ' is completing the statement in mid way.

Try :

system("perl -pe '\$_=\"11111\\n\$_\" if \$.==1;\$_.=\"2222\\n3333\\n\" if \$.==6' sample.txt");

thank you zedex and bartus11, it works fine now :):slight_smile: