Wednesday, March 26, 2008

Cygwin: Unix filenames from Windows filenames

Here's a bash script that will help Cygwin reference Windows filenames. It could work under /bin/sh, but I wrote is as part of a bash .profile, so I've only tested it there.


#!/bin/bash
#
# sanify - turn a Windows path name into a Unix name
# - turns drive letters into /cygdrive/drive,
# - flips slashes, removes enclosing quotes,
# - replaces unusual characters with '?'

function usage() { cat <<"EOF"
Usage: $1 'Windows filename'
... where 'Windows filename' only has to be in quotes if
it has special characters, such as backslashes or spaces.
This is free.
EOF
}

function sanify() {
echo ${@} | sed \
-e 's,^[A-Za-z]:,/cygdrive/&,'\
-e 's,:,,g' \
-e 's,\\,/,g' \
-e 's,^\",,g' \
-e 's,\"$,,g' \
-e 's,[^A-Za-z0-9_\.-],\?,g'
}

if [ -t ] ; then
[ -z "$@" ] && { usage "$0" }
sanify "${@}" else
for name in `cat` ; do
sanify "${name}"
done
fi