#!/usr/bin/perl # Based on: http://perlmonks.thepen.com/8991.html # # Extended to handle to->from conversion of the following # platforms: dos, mac, unix # # 20021125 miles@cmu.edu # use strict; use Getopt::Long; use File::Copy; my ($optFrom, $optTo, $optInFile, $optBackup); GetOptions('from=s' => \$optFrom, 'to=s' => \$optTo, 'infile=s' => \$optInFile, 'backup' => \$optBackup); my $usage = "Usage: $0 --from --to --infile [--backup]\n\nConverts line endings of text files from a given platform to line endings\nof a given platform. Allowable plaforms are:\n\tdos (CRLF)\n\tmac (CR)\n\tunix (LF)\nFrom and to platforms must be different\n\nOptional backup switch causes infile to be saved as another file with '.bak'\nappended to its name before the new file is written.\n"; if (!defined($optFrom) || !defined($optTo) || !defined($optInFile)) { print "$usage\n"; exit 1; } if (!defined($optBackup)) { $optBackup = 0; } my ($lineEndingFrom, $lineEndingTo); if ($optFrom eq $optTo) { print "$usage\n"; exit 1; } if ($optFrom eq 'unix') { $lineEndingFrom = "\012"; } elsif ($optFrom eq 'dos') { $lineEndingFrom = "\015\012"; } elsif ($optFrom eq 'mac' ) { $lineEndingFrom = "\015"; } else { print "$usage\n"; exit 1; } if ($optTo eq 'unix') { $lineEndingTo = "\012"; } elsif ($optTo eq 'dos') { $lineEndingTo = "\015\012"; } elsif ($optTo eq 'mac' ) { $lineEndingTo = "\015"; } else { print "$usage\n"; exit 1; } my @files; push(@files, $optInFile); for my $file ( @files ) { open FILE, $file or next; # thanks turnstep my @lines = ; close FILE; foreach my $i ( 0..$#lines ) { $lines[$i] =~ s/$lineEndingFrom/$lineEndingTo/g; } if ($optBackup) { copy($file, "$file.bak"); } open FILE,">$file"; print FILE @lines; close FILE; } # EOF