Remove blank lines from beginning of file

Discussion in 'Programming' started by rogan4567, Nov 14, 2009.

  1. #1
    I'm hopelessly stuck on this -- I'm trying to remove the blank lines from the beginning of a text file. (remove all lines up to when the first line with a-z characters shows up) I'm assuming that they're newline (\n), but I'm also trying with \r to strip them out to no avail.

    
    $text_filepath = "C:/web/htdocs/word2text/test";
    opendir(TFP, $text_filepath) || die("Cannot open directory");
    @textfiles = readdir(TFP);
    closedir(TFP); 
    
    foreach $file (@textfiles)
    {
     unless ( ($file eq ".") || ($file eq "..") )
     {
    $files_loc = "$text_filepath/$file";
    print "Opening $file<br>\n";
    open (ARTICLE, ">>", "$files_loc") || die "couldn't open the file!";
    while (<ARTICLE>) {
    if ($_ =~ m/[a-z]/i)  {last;}
    else {$_ =~ s/(.*)//g; print "Blank Line <br />\n";}
    }
    close(ARTICLE);
    }
    }
    
    Code (markup):
    If the above encounters a line with word characters (a-z) in it, it just moves on to the next file. However, I am not triggering the 'else', or I'm not doing something right.... It took me a few minutes to figure out how to read & parse Word files, but it's taking me hours to figure out how to remove empty lines from the beginning of a text file.

    This is perl, but I'm assuming that php would be similar enough so maybe somebody has an idea on what's wrong here.

    Any help would be appreciated.
     
    rogan4567, Nov 14, 2009 IP
  2. gabibeowulfx

    gabibeowulfx Active Member

    Messages:
    211
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    63
    #2
    I don't know perl but why don't you apply the following algorithm :

    1) split (explode) the file after the character \n so you'll have each line in to an array of lines
    2) while (empty line ) { go to next line}
    3) put back the remaining lines in the file and save it.
     
    gabibeowulfx, Nov 19, 2009 IP
  3. rogan4567

    rogan4567 Active Member

    Messages:
    103
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    55
    #3
    That would have worked, but I was able to fix the file beforehand by eliminating the possibility of empty leading lines while the file was being created.

    Thank you for the response.
     
    rogan4567, Nov 29, 2009 IP