#! /usr/bin/perl
use strict;
use warnings;
use Tie::File;
my $file = '/path/to/file.ext';
tie my @array,'Tie::File',$file or die $!;
$_ =~ s/,$/ / for(@array);
untie @array;
see Tie::File | [reply] [d/l] |
$ perl -p -i -e 's/,$/ /' somefile.txt
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
| [reply] [d/l] |
thanks for that, another new module to add to the list
| [reply] |
In general, to read/write to a file, you need to open the file read/write, and if you want to write back a line you just read, you need to seek back to the beginning for the line before writing. But it gets complicated if the line you are writing back have a different length. On Unix and Windows, files are just streams of bytes, neither the OS, nor the filesystem have any concept of a "lines" - lines are there for us humans.
The easy solution in your case would be to make use of either a temporary file, or to slurp in the entire file into memory. With many systems now having at least 256 Mb of memory, slurping in entire files isn't too bad (although I wouldn't do it with a 5 Gb file). Some untested code:
use Fcntl 'SEEK_SET';
open my $fh, "+<", $file or die;
local $/;
local $_ = <$fh>;
s/,(?=\n|$)//g;
seek $fh, 0, SEEK_SET or die;
print $fh $_ or die;
truncate $fh, tell $fh or die;
close $fh or die;
Do not forget the truncate, this is needed if you have actually deleted any commas - the text to write back will be shorter, and you don't want the trailing old part of the file.
And for a one-liner:
perl -pi -le 'BEGIN{$/=",\n"}' file
| [reply] [d/l] [select] |
If you know that each line has a ',' you can also use chop instead of the RE
| [reply] |
| [reply] |
this posting was absolutely well-formed and correct, but nobody posted a question matching to my answer, so I removed it... it was too early in the morning...
Please, dear NodeReaper, would you mind removing my posting
Best regards,
perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"
| [reply] |