|
我经常下载一些电子书和歌曲,有些文件名里有空格,有些又有下滑线,十分难看,为了使自己使用起来方便、好管理、看着顺眼,我写了一个小脚本将文件名里的空格和下滑线转换成连字符"-",并检查文件名里是否有多个"-"连在一起,如果有就将它们改成一个"-"。还有一些功能欠缺,例如将每个单词首字母大写(of, the, a除外)。使用时请小心,之前最好做个测试。已知存在的问题是当文件名里有[]时无法正常工作,会将整个文件名复制一遍。
[PHP]
#!/bin/bash
# This script turns underlines and blanks in filenames to hyphens
# Written by Neo Anderson <ZeeGeek@gmail.com>
# Jan 19 2005
DIR=$1
TEMP_FILE=/tmp/ul2h.tmp
btoh() {
exec < $TEMP_FILE
while read FILE_NAME
do
BASE_NAME="`basename "$FILE_NAME"`"
# change all blanks into hyphens
while echo "$BASE_NAME" | grep " "
do
BASE_NAME="`echo "$BASE_NAME" | sed s/' '/-/`"
done
# rename the target
mv "$FILE_NAME" "${FILE_NAME%"$(basename "$FILE_NAME")"}$BASE_NAME"
done
rm $TEMP_FILE
}
ultoh() {
exec < $TEMP_FILE
while read FILE_NAME
do
BASE_NAME="`basename $FILE_NAME`"
# change every underline to hyphen
while echo $BASE_NAME | grep _
do
BASE_NAME="`echo $BASE_NAME | sed s/_/-/`"
done
# rename the target
mv $FILE_NAME "${FILE_NAME%$(basename $FILE_NAME)}$BASE_NAME"
done
rm $TEMP_FILE
}
finalize() {
exec < $TEMP_FILE
while read FILE_NAME
do
BASE_NAME="`basename $FILE_NAME`"
# shorten hyphens
while echo $BASE_NAME | grep -e --
do
BASE_NAME="`echo $BASE_NAME | sed s/"--"/-/`"
done
# rename the target
mv $FILE_NAME "${FILE_NAME%$(basename $FILE_NAME)}$BASE_NAME"
done
rm $TEMP_FILE
}
usage() {
echo "Usage: ul2h.sh [directory...]"
}
if [ -z $DIR ]
then
usage
else
# get the file list of filenames containing blanks
find $DIR -type f -iname "* *" > $TEMP_FILE
btoh
# get the file list of directory names containing blanks
find $DIR -iname "* *" > $TEMP_FILE
btoh
# get the file list of filenames containing underlines
find $DIR -type f -iname "*_*" > $TEMP_FILE
ultoh
# get the file list of directory names containing underlines
find $DIR -iname "*_*" > $TEMP_FILE
ultoh
# check if there is any files which contain more than one hyphen
# together
find $DIR -iname "*--*" > $TEMP_FILE
finalize
fi
[/PHP] |
|