raj17 has asked for the wisdom of the Perl Monks concerning the following question:

i have a file containing patterns like this:
abcd
bcdsa
aptn
i want each line to be extracted and print it in a new file so according to example ill be getting 3 files in which each file will be having
abcd (in file1)
bcdsa(in file2) etc

  • Comment on Extracting each line in a file to new file seperately

Replies are listed 'Best First'.
Re: Extracting each line in a file to new file seperately
by Eliya (Vicar) on Feb 10, 2012 at 16:19 UTC

    If you want to learn some Perl (rather than just getting the job done — in which case you could use the split utility), the open function is the key to solve your task.

    That is, read the original file line by line, and for every line, open a new file for writing, and write the line to the respective file handle. The file name would comprise a counter variable, which you increment for every line.

    The orginal file can be read line by line as follows when you specify its file name on the command line:

    while (my $line = <>) { # ... do something with $line }

    Make an attempt yourself to fill in "...", and if you get stuck, post what you've tried so far.

      A little amendment to Eliya's solution (a little more talkative )
      while <INFILE> { $i++; open OUT ">$i.txt"; #do whatever with your line print OUT, "...whatever..."; close OUT; #just to be tidy :) }
Re: Extracting each line in a file to new file seperately
by umasuresh (Hermit) on Feb 10, 2012 at 16:09 UTC
    Read up on linux split command. This may be the easiest!

      ok so i have to do use split command:
      split -l 300 newfile.txt with looping k thank you for ur valuble suggestion

        Except that that will split your file into files with 300 lines each. If you want one line each, you'll need to use `split -l 1 file.orig new.`. Also, by default, split will use two-character lowercase alpha suffixes (aa .. zz) to name the new files, so it'll run out if you split into more than 676 chunks. Check the split man page for how to increase that.

        Aaron B.
        My Woefully Neglected Blog, where I occasionally mention Perl.