ファイル拡張子を一括変更する方法、一つのスクリプトで解決

場合によっては、すべての .txt ファイルを .md に変更するなど、ファイルの拡張子を一括で変更する必要があります。この記事では、バッチファイル(.bat)とシェルスクリプトを使用してこの目標を達成する方法について、詳細な手順とユーザーインタラクションのプロンプトを含めて紹介します。

バッチファイルの実装

バッチスクリプト(.bat)を作成し、ユーザーをステップごとに案内してファイル拡張子を一括変更するタスクを実行します。

1. バッチファイルの作成

rename_extension.bat という名前のファイルを作成し、次の内容をコピーします:

Terminal window
1
@echo off
2
setlocal enabledelayedexpansion
3
4
rem Step 1: Prompt user for the directory
5
set "dir="
6
set /p dir="Please enter the directory you want to modify: "
7
8
rem Step 2: Ask if user wants to include subdirectories
9
set "include_subdirs="
10
set /p include_subdirs="Do you want to include all subdirectories? (y/n): "
11
12
rem Step 3: Prompt user for the original and new file extensions
13
set "orig_ext="
14
set /p orig_ext="Enter the original file extension (without dot): "
15
set "new_ext="
16
set /p new_ext="Enter the new file extension (without dot): "
17
18
rem Step 4: Perform the renaming operation
19
if /i "%include_subdirs%"=="y" (
20
rem Include subdirectories
21
for /r "%dir%" %%f in (*.%orig_ext%) do (
22
set "filepath=%%f"
23
ren "%%f" "%%~nf.%new_ext%"
24
)
25
) else (
26
rem Do not include subdirectories
27
for %%f in ("%dir%\*.%orig_ext%") do (
28
set "filepath=%%f"
29
ren "%%f" "%%~nf.%new_ext%"
30
)
31
)
32
33
echo All matching files have been renamed.
34
pause

2. バッチファイルの実行

rename_extension.bat ファイルをダブルクリックし、プロンプトに従って情報を入力することで、指定したディレクトリ内のファイル拡張子を一括で変更できます。

シェルスクリプトの実装

シェルスクリプト(.sh)を作成し、ユーザーをステップごとに案内してファイル拡張子を一括変更するタスクを実行します。

1. シェルスクリプトの作成

rename_extension.sh という名前のファイルを作成し、次の内容をコピーします:

1
#!/bin/bash
2
3
# Step 1: Prompt user for the directory
4
read -p "Please enter the directory you want to modify: " dir
5
6
# Step 2: Ask if user wants to include subdirectories
7
read -p "Do you want to include all subdirectories? (y/n): " include_subdirs
8
9
# Step 3: Prompt user for the original and new file extensions
10
read -p "Enter the original file extension (without dot): " orig_ext
11
read -p "Enter the new file extension (without dot): " new_ext
12
13
# Step 4: Perform the renaming operation
14
if [ "$include_subdirs" = "y" ] || [ "$include_subdirs" = "Y" ]; then
15
# Include subdirectories
16
find "$dir" -type f -name "*.$orig_ext" -exec bash -c 'mv "$0" "${0%.*}.'$new_ext'"' {} \;
17
else
18
# Do not include subdirectories
19
find "$dir" -maxdepth 1 -type f -name "*.$orig_ext" -exec bash -c 'mv "$0" "${0%.*}.'$new_ext'"' {} \;
20
fi
21
22
echo "All matching files have been renamed."

2. スクリプトに実行権限を付与

ターミナルで次のコマンドを実行し、スクリプトに実行権限を付与します:

Terminal window
1
chmod +x rename_extension.sh

3. シェルスクリプトの実行

ターミナルで次のコマンドを実行し、プロンプトに従って情報を入力することで、指定したディレクトリ内のファイル拡張子を一括で変更できます:

Terminal window
1
./rename_extension.sh

まとめ

この記事では、バッチファイル(.bat)とシェルスクリプトを使用してファイル拡張子を一括変更する方法について、詳細な手順とユーザーインタラクションのプロンプトを含めて紹介しました。これらのスクリプトを使用することで、ファイル拡張子を簡単に一括で変更でき、作業効率を向上させることができます。