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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can you modify a file in-place? 1

Status
Not open for further replies.

menkes

Programmer
Nov 18, 2002
47
US
I have a file that I need to modify, but would like to do so without creating a new file. There are 2 form feeds in the file that must be removed. The first is near the top of the file...always at the start of line 52. The last form feed is the only thing on the last line of the file.

I know I can truncate the file to remove the last form feed:
open (FH, "+< $file");
while ( <FH> ) {
$addr = tell(FH) unless eof(FH);
}
truncate(FH, $addr);

Is there anyway to snip out that other form feed from line 52? It is always the first character on the line. But the actual amount of data prior to the 52nd line is unknown.
 
1. Read to an array
2. adjust array - remove what you want
3. set FH to start of file
4. write array to file
5. trunc file

done :)
 
Modiying espar's suggestion a little, just don't put the formfeeds in the array in the first place, e.g.
Code:
open (FH, "<menkes.txt") || die qq(Can't open "menkes.txt" for input!\n);
[b]my @arr = grep {!/^\f/} <FH>;[/b]
close (FH) || die qq(Can't close "menkes.txt"!\n);
open (FH, ">menkes.txt") || die qq(Can't open "menkes.txt" for output!\n);
print FH @arr;
close (FH) || die qq(Can't close "menkes.txt"!\n);
 
Good suggestions...both of them. I think I'll need to use espar's suggestion and handle the array elements. There are many form feeds in the file that are necessary, so I have to be careful to just remove the extraneous ones.
 
Okay, I didn't realize there were other formfeeds in the file that you wanted to leave in. See bolded lines.
Code:
open (FH, "<menkes.txt") || die qq(Can't open "menkes.txt" for input!\n);
[b]my @arr = <FH>;
pop(@arr);
@arr = (@arr[0..50], @arr[52..$#arr]);[/b]
close (FH) || die qq(Can't close "menkes.txt"!\n);
open (FH, ">menkes.txt") || die qq(Can't open "menkes.txt" for output!\n);
print FH @arr;
close (FH) || die qq(Can't close "menkes.txt"!\n);
 
Or
Code:
open (FH, "<menkes.txt") || die qq(Can't open "menkes.txt" for input!\n);
[b]my @arr;
while (<FH>) {
    last if eof;
    push @arr, $_ unless $. == 52;
}
[/b]
close (FH) || die qq(Can't close "menkes.txt"!\n);
open (FH, ">menkes.txt") || die qq(Can't open "menkes.txt" for output!\n);
print FH @arr;
close (FH) || die qq(Can't close "menkes.txt"!\n);

 
how about a cli one-liner?
Code:
# perl -pi -e "$.==52 && s/^\f// or eof && s/\f//" infile.txt
:)

________________________________________
Andrew

I work for a gift card company!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top