All Things Patrick - Working Hard to be Lazy!

  • home
  • blog
  • links
Home › Blogs › patrick's blog

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
  • Shell Scripting
  • patrick's blog
  • Add new comment

User login

What is OpenID?
Connect
Sign in using Facebook
  • Log in using OpenID
  • Cancel OpenID login
  • Create new account
  • Request new password

Pages

  • About Me
  • About My Boxen
  • Quotes
  • 3d Graphics
  • Color Picker App
  • Resume
  • dailymile
  • facebook
  • twitter

Tags in Tags

CSS Design Development Entertainment EVE-Online Firefox Friends Games Hardware HTML Internet Explorer JavaScript Job Movies & TV Operating Systems Personal PHP Security Windows YouTube
more tags

Blogroll

  • 456 Berea Street
  • Anne van Kesteren’s Weblog
  • Clients From Hell
  • Derick Rethans' blog
  • Doug Seitz
  • Eric Meyer
  • Terry Chay
  • The FAIL Blog

Powered by Drupal, an open source content management system
  • home
  • blog
  • links