Rename Files With Spaces or Changing From Uppercase to lowercase
patrick — Thu, 2007-07-05 15:31
This info has been around for a while, but I thought I'd post it so I wouldn't have to go hunting for the info again.
Rename files with capital letters in the filename to all lowercase -
#!/bin/bash
for i in $@; do
new=`echo $i | tr 'A-Z' 'a-z'`;
if [ "$i" != "$new" ]; then
mv "$i" "$new";
fi;
done;
Or if you'd rather not use a shell script file to do it -
files="file1 file2"; \\
for i in `echo $files`; do \\
new=`echo $i | tr 'A-Z' 'a-z'`; \\
if [ "$i" != "$new" ]; then \\
mv "$i" "$new"; \\
fi; \\
done;
If you're dealing with files that have spaces in the names you can do something like this -
for i in *.xls; do \\
new=`echo $i | sed -r "s/ +/-/g"`; \\
mv "$i" "$new"; \\
done;
If you're needing something a bit more complex or you're pulling data out of a text file via cat you'll need to convert spaces prior to doing a loop. In this example I'm doing a find on a directory tree and converting names as I go -
files=`find -name '*.xls' | sed -r "s/ /\\*-/g"`; \\
for i in `echo $files`; do \\
file=`echo $i | sed -r "s/\*-/ /g"`; \\
dir=`echo $file | sed -r "s/\\/[^\\/]+$/\\//"; \\
newname=`echo $file | sed -r "s/.+\\/([^\\/]+)$/\\1/" | sed -r "s/ +/-/g"`; \\
if [ "$file" != "$dir$newname" ]; then \\
mv "$file" "$dir$newname"; \\
fi; \\
done;
The checking portion isn't necessary afaik, but it prevents the mv utility from outputing lots of information stating 'filex' and 'filex' are the same file
.
Trackback URL for this post:
http://blog.whitelionsoft.com/trackback/51