How do I rename files in sub directories?

Viewed 97313

Is there any way of batch renaming files in sub directories?

For example:

Rename *.html to *.htm in a folder which has directories and sub directories.

11 Answers

Windows command prompt: (If inside a batch file, change %x to %%x)

for /r %x in (*.html) do ren "%x" *.htm

This also works for renaming the middle of the files

for /r %x in (website*.html) do ren "%x" site*.htm
find . -regex ".*html$" | while read line;
 do 
    A=`basename ${line} | sed 's/html$/htm/g'`;
    B=`dirname ${line}`;
    mv ${line} "${B}/${A}";
 done

In python

import os

target_dir = "."

for path, dirs, files in os.walk(target_dir):
    for file in files:
        filename, ext = os.path.splitext(file)
        new_file = filename + ".htm"

        if ext == '.html':
            old_filepath = os.path.join(path, file)
            new_filepath = os.path.join(path, new_file)
            os.rename(old_filepath, new_filepath)

In Bash, you could do the following:

for x in $(find . -name \*.html); do
  mv $x $(echo "$x" | sed 's/\.html$/.htm/')
done

I'm sure there's a more elegant way, but here's the first thing that popped in my head:

for f in $(find . -type f -name '*.html'); do 
    mv $f $(echo "$f" | sed 's/html$/htm/')
done
In bash use command rename :)

 rename 's/\.htm$/.html/' *.htm

 # or

 find . -name '*.txt' -print0 | xargs -0 rename 's/.txt$/.xml/'

 #Obs1: Above I use regex \. --> literal '.'  and  $ --> end of line
 #Obs2: Use find -maxdepht 'value' for determine how recursive is
 #Obs3: Use -print0 to avoid 'names spaces asdfa' crash!

On Linux, you may use the 'rename' command to rename files in batch.

AWK on Linux. For the first directory this is your answer... Extrapolate by recursively calling awk on dir_path perhaps by writing another awk which writes this exact awk below... and so on.

ls dir_path/. | awk -F"." '{print "mv file_name/"$0" dir_path/"$1".new_extension"}' |csh

there is pretty powerfull forfiles command:

forfiles /? gives u hint of what is possible with the command. in this case it can be used like:

forfiles /S /M *.html /C "cmd /c rename @file @fname.htm"
Related