Posted By

jonhenshaw on 07/27/08


Tagged

commandline convert filename uppercase lowercase


Versions (?)

Howto Convert Filenames to All Lowercase


 / Published in: Bash
 

URL: http://www.linuxjournal.com/content/convert-filenames-lowercase

Line 6 starts a loop (which ends with line 15). The ls command returns a list of filenames which are sequentially assigned to the shell variable x. The if test (lines 8 through 10) checks to see if the current filename is that of a plain file. If not, the remainder of the statements in the current loop iteration are skipped.

If line 11 is to be executed we know that we have an ordinary file. Using tr we convert the filename to lowercase and assign the new name to the shell variable lc. Line 12 then checks to see if the lowercase version of the name differs from the original. If it does, line 13 is executed to change the name of the original file to the new lowercase name. The -i option causes the mv to prompt for confirmation if executing the command would overwrite an existing filename. __________________________

  1. #!/bin/sh
  2. # lowerit
  3. # convert all file names in the current directory to lower case
  4. # only operates on plain files--does not change the name of directories
  5. # will ask for verification before overwriting an existing file
  6. for x in `ls`
  7. do
  8. if [ ! -f $x ]; then
  9. continue
  10. fi
  11. lc=`echo $x | tr '[A-Z]' '[a-z]'`
  12. if [ $lc != $x ]; then
  13. mv -i $x $lc
  14. fi
  15. done

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: snipuserx on October 5, 2008

Your script does not handle spaces and other stuff in filenames correctly. ls is a really ugly novice mistake. Heres a much better version, it removes the directory check and interactive crap also.

!/bin/bash -xe

convert all files in the current directory to lower case

for x in * do lc=$(echo "$x" | tr "[A-Z]" "[a-z]") if [[ $lc != $x ]]; then mv "$x" "$lc" fi done

Posted By: snipuserx on October 5, 2008

ok, the automatic markup/down crap ruined my comment, and there is no obvious way to post code in a comment. This site = fail.

You need to login to post a comment.