Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to remove empty line

Status
Not open for further replies.
Apr 30, 2003
56
US
I have a document with its last line empty. How can I use perl to ask it to read through the whole document and remove the last empty line? I don't whole how many exact lines are in the document.
 
Try this. It's quick and dirty but should work:
Code:
open(IN,"<some_document.txt");
@lines = <IN>; # dump all doc lines in an array
close IN;

pop @lines; # takes the last line off and throws it away

# assemble all lines into a single string, for convenience
$doc = join("",@lines);

# print doc contents, minus last line, back
# to original file.
open(OUT,">some_document.txt");
print OUT $doc;
close OUT;

--G
 
shouldn't
Code:
$doc = join("",@lines);
not be
Code:
$doc = join("\n",@lines);
 
Sorry, forget my remark. I am so used to chomp the retrieved data that I forgot that the \n is included.
 
if you have access to *nix utilities:

ex file <<!
> \$g/^$/d
> wq
> !

 
I wonder if you could put it inside a while loop like so:

while(<READFILE>){

chomp; #cut off \n
next unless length;

#then do something else if it has length

}
 
Not really, nawlej. That would remove ANY blank line in the file. Eileen1017 specified that only the last line in the file should be removed, so it isn't even necessary to check for blankness.

However, if what we wanted WAS to remove all blank (totally empty, no whitespace) lines - you'd be dead-on. Your suggestion could work like this:
Code:
open(READFILE,"<somefile.txt");
while(<READFILE>){
  chomp;  #cut off \n
  next unless length;
  
  #then do something else if it has length
  push @lines;
}
close READLINE;

# dump the file back out
$lines = join(/\n/,@lines);
open(OUT,">somefile.txt");
print OUT $lines;
close OUT;


--G
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top