---
slug: "複数ファイルをエディターを使ってファイル名を一括置換するスクリプト"
title: "A Script to Batch Rename Multiple Files Using an Editor"
description: "\n\n\nWhen you start the program, a list of files is displayed in the editor.\nYou can modify and save the list."
url: "https://www.ytyng.com/en/blog/複数ファイルをエディターを使ってファイル名を一括置換するスクリプト"
publish_date: "2014-01-29T10:41:59Z"
created: "2014-01-29T10:41:59Z"
updated: "2026-02-27T05:45:04.563Z"
categories: ["Python"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/3553eef3629e4fb38011ce26de47122b.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# A Script to Batch Rename Multiple Files Using an Editor

<div class="document">


<p>When you start the program, a list of files is displayed in the editor.
You can modify and save the list.</p>
<p>The program will rename the files according to your modifications.</p>
<p>Usage:</p>
<pre class="literal-block">bulk-rename
bulk-rename *.txt
bulk-rename temp/
</pre>
<p>The arguments are passed directly to the ls command.</p>
<p>Be careful as using options like -l might cause issues.</p>
<p>It seems safe to strip any /-w+/ patterns if they're given as arguments.</p>
<pre class="literal-block">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import sys
import os

TEMP_FILE_NAME = '/tmp/bulk-rename-file-names'
EDITOR = 'vim'


def main():
    command_result = subprocess.check_output(["ls", "-1"] + sys.argv[1:])
    file_names = command_result.splitlines()

    with open(TEMP_FILE_NAME, 'w') as fp:
        fp.write('\n'.join(file_names))

    subprocess.check_call([os.environ.get('EDITOR', EDITOR), TEMP_FILE_NAME])

    with open(TEMP_FILE_NAME, 'r') as fp:
        destination_file_names = fp.readlines()

    for source, destination in zip(file_names, destination_file_names):
        if source and destination:
            destination = destination.strip()
            if source != destination:
                print "{} -> {}".format(source, destination)
                os.rename(source, destination)

    os.unlink(TEMP_FILE_NAME)


if __name__ == '__main__':
    main()
</pre>
</div>
