What can open source software do for you?

Prometheon, Inc Consulting

Simple Perl script to remove illegal characters

August 22nd, 2008 by rnix

Insert this script inside of the root directory containing all of the files and folders that contain illegal characters.

Run this command:  find -d . -print0 | xargs -0 /Users/$HOME/Desktop/rename_for_windows (or whatever you named your file)

The script:

#!/usr/bin/perl -w

# This script renames all the files supplied as command-line args
# where necessary so that the filename is acceptable to MS Windows
# Cameron Hayne (macdev@hayne.net), June 2004

use strict;

chomp(@ARGV = <STDIN>) unless @ARGV;

# The Microsoft document at
# http://support.microsoft.com/default…b;EN-US;100108
# says that the following characters are not allowed in filenames
# in each of the specified filesystems:
# FAT:   .  “  /  \  [  ]  |  :  ;  ,  =
# NTFS:  ?  “  /  \  <  >  |  :  *

# We don’t do anything with the dot (.) since it clearly is allowable
# in spite of what that document says.
# And we don’t do anything with the slash (/) since that character
# will not occur in OS X filenames and modifying it would cause
# troubles when a file path (with directories) is specified.
# The changing of the filenames is done via the ‘tr’ statements below.
# Each occurence of a character in the first curly brackets
# is replaced by the character in the second curly brackets.

foreach my $filename (@ARGV)
{
my $orig_filename = $filename;

$filename =~ tr{\\}{-};
$filename =~ tr{*?}{X};
$filename =~ tr{”><[]|:;,’=}{_};

unless ($filename eq $orig_filename)
{
print “About to rename $orig_filename to $filename\n”;
if (-e $filename)
{
print “Oops, there already exists a file named $filename\n”;
print “Skipping the rename - you will have to do it manually\n”;
}
else
{
rename($orig_filename, $filename);
}
}
}

Posted in Software |

Comments are closed.