//View Tip #544
Similar Tips
» Find last modified files on a filesystem
» Bash efficiency formula ;-)
» Fix the previous command
» list the most recent files in a directory
» Bash

 

Latest tips by RSS
Click here to subscribe
Follow Shell-Fu on Twitter
Click here to follow
Follow Shell-Fu on identi.ca
Click here to follow
This tip is inspired by #27 ( http://www.shell-fu.org/lister.php?id=27 ) which I think is misleading, here's a much more reliable and efficient version:

rename_ext() {
   local filename
   for filename in *."$1"; do
     mv "$filename" "${filename%.*}"."$2"
   done
}


use it like:


rename_ext php html


to rename all .php files to .html in the current directory.


View Comments »




Comments 

Add your comment

Comments are currently disabled
Jon
That looks wonderfully useful.  Could you explain what % does in this case?  "man bash" hurt my brain.
Posted 2009-02-24 20:38:06
anonymous
user@host$ man bash
...
    ${parameter%word}
    ${parameter%%word}
         The word is expanded to produce a pattern  just  as  in
         pathname  expansion.  If the pattern matches a trailing
         portion of the expanded value of  parameter,  then  the
         result of the expansion is the expanded value of param-
         eter with the  shortest  matching  pattern  (the  ``%''
         case) or the longest matching pattern (the ``%%'' case)
         deleted.  If parameter is @ or *, the  pattern  removal
         operation  is  applied  to each positional parameter in
         turn, and the expansion  is  the  resultant  list.   If
         parameter is an array variable subscripted with @ or *,
         the pattern removal operation is applied to each member
         of  the  array in turn, and the expansion is the resul-
         tant list.
...
Posted 2009-02-25 13:55:42
anonymous
Cool function, thanks!
The only thing I would change here is the file list:
[code]
function chext()
{
 local fname
 local new_ext="$1"
 shift
 IFS=$'\n'
 for fname in $@
 do
   mv "$fname" "${fname%.*}.$new_ext"
 done
}
[/code]

And the usage would be:
[code]
chext new_ext *.old_ext
[/code]
Posted 2009-02-25 14:26:25

Home Latest Browse Top 25 Random Hall Of Fame Contact Submit