从终端递归地将所有文件和文件夹重命名为标题大小写

从终端递归地将所有文件和文件夹重命名为标题大小写

我是一个新手,我到处寻找这个,我也尝试将小写重命名命令与一些正则表达式结合起来以获得标题大小写而不是小写,但我不太成功。

此命令将给定文件夹内的所有内容(文件+文件夹)转换为小写:

while IFS= read -r -d '' file; do mv -b -- "$file" "${file,,}"; done < <(find . -depth -name '*[A-Z]*' -print0)

这是我对标题大小写的尝试,它可以起作用,但不是递归的:

find . -name "*.flac" -print0 | while read -d $'\0' file; do rename 's/(^|[\s\(\)\[\]_-])([a-z])/$1\u$2/g' *; done

这些只是我的一些尝试,如果有更好、更短的解决方案,我会更喜欢它们。

你能帮帮我吗?提前谢谢!

编辑:我忘了说了,我的文件看起来像这样:“09 - the Road to Home - Amy MacDonald.flac”;应该重命名为“09 - The Road To Home - Amy Macdonald.flac”。请注意,单词中间已经有标题大小写的单词以及大写字母。

答案1

要使用下面的脚本,您只需要具备粘贴能力:)

如何使用

  1. 将下面的脚本粘贴到一个空文件中,并将其保存为(例如)rename_title.py
  2. 使其可执行(为了方便)chmod u+x rename_title.py
  3. 使用要重命名的目录作为参数来运行它:

    /path/to/rename_title.py <directory/to/rename>
    

剧本

#!/usr/bin/env python3
import os
import sys
import shutil

directory = sys.argv[1]

skip = ["a", "an", "the", "and", "but", "or", "nor", "at", "by", "for", "from", "in", "into", "of", "off", "on", "onto", "out", "over", "to", "up", "with", "as"]
replace = [["(", "["], [")", "]"], ["{", "["], ["}", "]"]]
def exclude_words(name):
    for item in skip:
        name = name.replace(" "+item.title()+" ", " "+item.lower()+" ")
    # on request of OP, added a replace option for parethesis etc.
    for item in replace:
        name = name.replace(item[0], item[1])
    return name

for root, dirs, files in os.walk(directory):
    for f in files:
        split = f.find(".")
        if split not in (0, -1):
            name = ("").join((f[:split].lower().title(), f[split:].lower()))
        else:
            name = f.lower().title()
        name = exclude_words(name)
        shutil.move(root+"/"+f, root+"/"+name)
for root, dirs, files in os.walk(directory):
    for dr in dirs:
        name = dr.lower().title()
        name = exclude_words(name)
        shutil.move(root+"/"+dr, root+"/"+name)

例子:

a file > A File
a fiLE.tXT > A File.txt
A folder > A Folder
a folder > A Folder

并且更加复杂,不包括["a", "an", "the", "and", "but", "or", "nor", "at", "by", "for", "from", "in", "into", "of", "off", "on", "onto", "out", "over", "to", "up", "with", "as"]

down BY the rIVER for my uncLE To get water.TXT

变成:

Down By the River for My Uncle to Get Water.txt

等等,它只是使所有文件和文件夹(递归)标题大小写,扩展名小写。

编辑:我根据歌曲标题的大写规则添加了所有不需要大写的冠词、连词和介词。

答案2

如果您使用find's -exedir,则名称将通过任何删除路径名前导部分的命令传递,例如./sOmE fILE。然后,您可以将每个以前导/或空格开头的单词字符序列改为标题大小写,例如

find path/ -execdir rename -nv -- 's/(?<=[\/\s])(\w)(\w*)/\u$1\L$2/g' {} +

相关内容