如何批量重命名文件後綴,一個腳本搞定
- 697字
- 3分鐘
- 2024-07-18
在某些情況下,我們可能需要批量重命名文件的擴展名,例如將所有 .txt
文件改為 .md
。本文將詳細介紹如何使用批處理文件(.bat)和Shell腳本來實現這個目標,包括詳細的步驟和用戶交互提示。
批處理文件實現
我們將編寫一個批處理腳本(.bat),它會一步步引導用戶完成批量重命名文件擴展名的任務。
1. 創建批處理文件
創建一個名為 rename_extension.bat
的文件,並將以下內容複製到其中:
1@echo off2setlocal enabledelayedexpansion3
4rem Step 1: Prompt user for the directory5set "dir="6set /p dir="Please enter the directory you want to modify: "7
8rem Step 2: Ask if user wants to include subdirectories9set "include_subdirs="10set /p include_subdirs="Do you want to include all subdirectories? (y/n): "11
12rem Step 3: Prompt user for the original and new file extensions13set "orig_ext="14set /p orig_ext="Enter the original file extension (without dot): "15set "new_ext="16set /p new_ext="Enter the new file extension (without dot): "17
18rem Step 4: Perform the renaming operation19if /i "%include_subdirs%"=="y" (20 rem Include subdirectories21 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 subdirectories27 for %%f in ("%dir%\*.%orig_ext%") do (28 set "filepath=%%f"29 ren "%%f" "%%~nf.%new_ext%"30 )31)32
33echo All matching files have been renamed.34pause
2. 運行批處理文件
雙擊 rename_extension.bat
文件,按照提示輸入相應的信息,即可批量重命名指定目錄下的文件擴展名。
Shell腳本實現
我們將編寫一個Shell腳本(.sh),它會一步步引導用戶完成批量重命名文件擴展名的任務。
1. 創建Shell腳本
創建一個名為 rename_extension.sh
的文件,並將以下內容複製到其中:
1#!/bin/bash2
3# Step 1: Prompt user for the directory4read -p "Please enter the directory you want to modify: " dir5
6# Step 2: Ask if user wants to include subdirectories7read -p "Do you want to include all subdirectories? (y/n): " include_subdirs8
9# Step 3: Prompt user for the original and new file extensions10read -p "Enter the original file extension (without dot): " orig_ext11read -p "Enter the new file extension (without dot): " new_ext12
13# Step 4: Perform the renaming operation14if [ "$include_subdirs" = "y" ] || [ "$include_subdirs" = "Y" ]; then15 # Include subdirectories16 find "$dir" -type f -name "*.$orig_ext" -exec bash -c 'mv "$0" "${0%.*}.'$new_ext'"' {} \;17else18 # Do not include subdirectories19 find "$dir" -maxdepth 1 -type f -name "*.$orig_ext" -exec bash -c 'mv "$0" "${0%.*}.'$new_ext'"' {} \;20fi21
22echo "All matching files have been renamed."
2. 賦予腳本執行權限
在終端中運行以下命令,為腳本賦予執行權限:
1chmod +x rename_extension.sh
3. 運行Shell腳本
在終端中運行以下命令,按照提示輸入相應的信息,即可批量重命名指定目錄下的文件擴展名:
1./rename_extension.sh
總結
本文介紹了如何使用批處理文件(.bat)和Shell腳本批量重命名文件擴展名,並提供了詳細的步驟和用戶交互提示。通過這些腳本,我們可以輕鬆地批量修改文件擴展名,提高工作效率。