By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,589 Members | 1,209 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,589 IT Pros & Developers. It's quick & easy.

How to insert a line to a file.

P: 1
Hi, Perl is new to me. I am trying to insert a line to a file. Ex: I have a file (trial.txt), content:
ZZZZ
AAA
DDDD

I am trying to insert CCC below AAA.
MY perl command:
Expand|Select|Wrap|Line Numbers
  1. open (FILE,"+>>C:\\Documents and Settings\\trial.txt\n")|| die "can't open file";
  2. while(<FILE>)
  3. {        
  4.         if(/AAA/)
  5.         {
  6.         print FILE "CCC\n"; 
  7.  
  8.        }
  9.  
  10. }#end while
  11. close(FILE);
  12.  
The ouuput I get:
ZZZZ
AAA
DDDDZZZZ
AAA
CCC
Where else what I need is:
ZZZZ
AAA
CCC
DDDD

It appends the whole file again and replaces the next line after AAA with CCC, where else what I need is to insert CCC in the existing file below AAA. Thanks to advise. :)
Dec 8 '10 #1
Share this Question
Share on Google+
1 Reply


P: 41
You are trying to read and write from the same file. Plus, it is a text file. This is asking for trouble.

I suggest that you create a new file (with the lines inserted), and after you are done, move the new file to the old one.
Dec 9 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.