deo*_*eox 2 command-line scripts perl rename
我使用 xmbc 来查看我的电视节目。在开始使用xmbc之前,我批量下载了《漂白》的前几季。我能说什么,我是动漫迷;-)。它们被命名为:“bleachxx.mp4”,其中 xx 是与整个系列相关的剧集编号,而不是与季节相关的剧集编号。所以“bleach21.mp4”是第二季的第1集,也是第21集。然而,这些文件本身被划分到它们自己的季节文件夹中。
我知道您可以使用“重命名”命令批量重命名文件。使用本指南对其进行大量修改后:http : //tips.webdesign10.com/how-to-bulk-rename-files-in-linux-in-the-terminal我得到了这个命令:
rename -n 's/.*(\d{2}).*$/Bleach S0XE$1/' *
Run Code Online (Sandbox Code Playgroud)
问题是该命令会将所有文件重命名为“Bleach S0XExx”,但由于文件具有整体文件编号,bleach52.mp4 --> 'Bleach S03E52.mp4',而第 3 季显然没有 52 集。
那么,我想知道,是否有任何方法可以将数学运算应用于文件重命名。这将解决这个问题,因为我可以用总数减去前几季的剧集数并基本上得到季数。
示例:如果第 1 季有 20 集,则 25-20=5,因此第 25 集是第 2 季的第 5 集,重命名将照常进行。
那么,无论如何,是否可以通过应用数学运算来更改重命名的值?
PS我很抱歉冗长的解释,但我不确定如何或者如果没有它我的问题是否会清楚。
如果您足够专注于修改正则表达式(在您提供的示例中),那么我建议更进一步并编写一个小脚本 - 例如,在 Python 中。通过这种方式,您将能够对文件名执行任何转换。
我估计 python 脚本的长度不会超过 15-20 行,所以这绝对不是一项艰巨的任务。当您尝试时,仅使用正则表达式会受到更多限制。
这是我对此类脚本的看法:
#!/usr/bin/python
import os,re
files = os.listdir('.')
SEASONS = (
(1, 1, 3), # the format is - season number, first episode, last episode
(2, 50,52),
(3, 53,55),
(4, 56,99),
)
for f in files:
# skip all files which are not .mp4
if not f.endswith(".mp4"):
continue
# find the first number in the filename
matches = re.findall("\d+", f)
if not len(matches):
print "skipping", f
num = int(matches[0])
for season in SEASONS:
if num <= season[2]:
season_num = season[0]
ep_num = num - season[1] + 1
new_file_name = "BleachS%02dE%02d.mp4" % (season_num, ep_num)
# This is for testing
print "%s ==> %s" % (f, new_file_name)
# Uncomment the following when you're satisfied with the test runs
# os.rename(f, new_file_name)
break
print "Done"
Run Code Online (Sandbox Code Playgroud)
看起来我低估了脚本大小(它是 36 行 atm),但我确定如果你使用这段代码去 stackoverflow,你会得到很多更优雅的建议
就因为我说可以15行...下面是20行,其中5行是配置:P
#!/usr/bin/python
import os, re, glob
SEASONS = (
{'num':1, 'first':1, 'last':3}, # the format is - season number, first episode, last episode
{'num':2, 'first':50, 'last':52},
{'num':3, 'first':53, 'last':55},
{'num':4, 'first':56, 'last':99},
)
files = glob.glob('bleach*.mp4')
for f in files:
num = int(re.findall("\d+", f)[0]) # find the first number in the filename
for season in SEASONS:
if num > season['last']: continue
new_file_name = "BleachS%02dE%02d.mp4" % (season['num'], num - season['first'] + 1)
print "%s ==> %s" % (f, new_file_name) # This is for testing
# os.rename(f, new_file_name) # Uncomment this when you're satisfied with the test runs
break
Run Code Online (Sandbox Code Playgroud)