「変数」を使用してファイル名を一括変更する方法は?

「変数」を使用してファイル名を一括変更する方法は?

私はテレビ番組を見るのに xmbc を使っています。xmbc を使い始める前に、「Bleach」の最初の数シーズンを一括ダウンロードしました。何と言っても、私はアニメファンですから ;-)。これらの名前は「bleachxx.mp4」で、xx はエピソード番号です。全シリーズ、シーズンではありません。したがって、「bleach21.mp4」は第 2 シーズンの第 1 話であり、全体では 21 番目のエピソードです。ただし、ファイル自体は独自のシーズン フォルダーに分割されています。

「rename」コマンドを使用して、ファイルを一括で名前変更できることは知っています。このガイドを使用して、いろいろ試した結果、次のようになりました。http://tips.webdesign10.com/how-to-bulk-rename-files-in-linux-in-the-terminalこのコマンドを受け取りました:

rename -n 's/.*(\d{2}).*$/Bleach S0XE$1/' *

問題は、コマンドによってすべてのファイルの名前が「Bleach S0XExx」に変更されるが、ファイルには全体のファイル番号があるため、シーズン 3 に 52 のエピソードがないことが明らかであるにもかかわらず、bleach52.mp4 --> 'Bleach S03E52.mp4' となることです。

では、ファイル名の変更に数学的演算を適用する方法があるかどうか知りたいです。これにより、前のシーズンのエピソードの数から全体の数を減算して、基本的にシーズン番号を取得できるため、問題は解決します。

例: シーズン 1 に 20 のエピソードがある場合、25-20=5 となり、25 番目のエピソードはシーズン 2 の 5 番目のエピソードとなり、名前の変更は通常どおり実行されます。

では、数学演算を適用して名前変更の値を変更する方法はありますか?

追伸:説明が長くて申し訳ありませんが、説明が長すぎて質問が明確にならないか、またどのように説明すればいいのかわからなかったのです。

答え1

正規表現をいじくり回すのに熱心であれば (提供されている例のように)、もう一歩進んで、たとえば 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"

スクリプトのサイズを過小評価していたようです(現時点では36行です)。ただし、このコードで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

答え2

Pythonスクリプトを書きました

import sys
import os
import glob
import re

def rename():
    episode_counts = (0, 20, 41, 63)
    episode_pairs = []
    for index, num in enumerate(episode_counts):
        if index < len(episode_counts) - 1:
            episode_pairs.append((num, episode_counts[index+1]))

    episodes = glob.glob(os.path.join(sys.argv[1], '*'))

    for episode in episodes:
        match = re.search('.*(\d{2}).*$', os.path.basename(episode))
        episode_num = match.group(1)

        for season, pair in enumerate(episode_pairs):
            if int(episode_num) in range(pair[0]+1, pair[1]+1):
                dirname = os.path.dirname(episode)
                path = os.path.join(dirname, 'Bleach S{0}E{1}'.format(season+1, episode_num))
                os.rename(episode, path)

if __name__ == "__main__":
    rename()

私は Python について本当に初心者です (練習のためにこれを書いた理由の 1 つです)。そのため、これはおそらく世界最高のスクリプトではありません。しかし、いくつかのテスト ファイルで試してみましたが、うまく機能しているようです。

episode_counts = ...シーズンの最後のエピソード番号の一番上の行を編集するだけです。私は最初の3つをこのページ。

コードを次のように保存しepisode_renamer.py、 で使用しますpython episode_renamer.py /path/to/episodes/

答え3

リポジトリには、一括名前変更オプションを備えた Thunar というファイル マネージャーがあります。

詳細については、次のサイトをご覧ください。 http://thunar.xfce.org/pwiki/documentation/bulk_renamer

thunar は、ソフトウェア センターまたはコマンド ラインで次のようにインストールできます。

sudo apt-get install thunar

これを bash で実行したり、コードを記述したりする方法もありますが、グラフィカル ツールを使用すると、おそらく目的のものをより早く得ることができます。

答え4

この馬を鞭打ち続けるには...これが一度限りの名前変更であれば、私は次のような使い捨てのものを実行します:

cd /path/to/stuff
ls bleach*-lq.mp4 >x
paste x x >y
sed 's-^-mv -' <y >z
vim z    # or use your favorite editor
           # to rename the files manually
bash -x z
rm x y z

複数回使用する場合、また複数の種類のエピソードに使用する場合は、Python が最適であり、上記の例で十分です。

関連情報