How do I rename files in sub directories?

前端 未结 15 1338
臣服心动
臣服心动 2020-12-04 11:10

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

For example:

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

相关标签:
15条回答
  • 2020-12-04 11:44

    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)
    
    0 讨论(0)
  • 2020-12-04 11:48

    On Unix, you can use rnm:

    rnm -rs '/\.html$/.htm/' -fo -dp -1 *
    

    Or

    rnm -ns '/n/.htm' -ss '\.html$' -fo -dp -1 *
    

    Explanation:

    1. -ns : name string (new name). /n/ is a name string rule that expands to the filename without the extension.
    2. -ss : search string (regex). Searches for files with match.
    3. -rs : replace string of the form /search_regex/replace_part/modifier
    4. -fo : file only mode
    5. -dp : depth of directory (-1 means unlimited).
    0 讨论(0)
  • 2020-12-04 11:50

    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
    
    0 讨论(0)
  • 2020-12-04 11:52

    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
    
    0 讨论(0)
  • 2020-12-04 11:54

    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
    
    0 讨论(0)
  • 2020-12-04 11:54

    Total Commander which is a file manager app, lets you list & select all files within its dir & sub-dirs, then you can run any of the total commander operations on them. one of them being: multi-rename the selected files.

    0 讨论(0)
提交回复
热议问题