Convert UNIX linefeeds to Windows end of line characters

I needed a file to do this, so cooked up a twenty minute hack. I’m not expert in the ways of any programming language, but write code that’s designed to be easily read and modified. Here’s a good basic template as well as a useful utility for converting UNIX text files to Windows, including removal of linefeeds (CRLF in Windows, LF in UNIX, CR on a Mac) so that you can easily translate UNIX files to Windows and old-school (pre-OS X) Macintoshes. There are people selling utilities to do this, but why would you need one, if you’ve got Perl installed?


#!/usr/bin/perl --

### use command line argument or default
$targetdir = "./";
$targetdir = $ARGV[0];

### setup variables
my @contents = "";
my $contentscounter = 0;

### main execution

chdir $targetdir;
&browseDir;
exit(0);

### functions

sub browseDir {

opendir (TARGETDIR, "./");
foreach my $file (sort readdir TARGETDIR) {
unless($file =~ m/^\./) {
if (-d $file) {
chdir $file;
browseDir($file);
chdir "../";
} # if directory file
else {
changeLF($file);
} # end else
} # end unless
} # foreach my file
close (TARGETDIR);
} # end browseDir

sub changeLF {

$targetfile = @_[0];

### load file into variable
open (TARGETFILE,"$targetfile") || die "Couldn't open targetfile: $!\n";
@contents = ;
close (TARGETFILE);

### transform variable
foreach $fileline (@contents) {
chomp($fileline);
}

### write file
open(TARGETFILE, ">$targetfile") || die "Cannot open targetfile: $!\n";
foreach $fileline (@contents) {
print TARGETFILE $fileline . "\r\n";
}
close (TARGETFILE);

} # end ChangeLF

Leave a Reply