批量去除文件后缀的脚本

wen 实用脚本 3

本文目录导读:

批量去除文件后缀的脚本

  1. Windows (PowerShell)
  2. Windows (CMD/Batch)
  3. Linux/macOS (Bash)
  4. Python (跨平台)
  5. 使用注意事项
  6. 安全用法示例

Windows (PowerShell)

# 去除当前目录下所有文件的后缀
Get-ChildItem -File | Rename-Item -NewName { $_.BaseName }
# 去除特定类型文件的后缀(如.txt)
Get-ChildItem -File *.txt | Rename-Item -NewName { $_.BaseName }
# 递归处理子文件夹
Get-ChildItem -File -Recurse | Rename-Item -NewName { $_.BaseName }

Windows (CMD/Batch)

@echo off
setlocal enabledelayedexpansion
:: 去除当前目录下所有文件的后缀
for %%f in (*.*) do (
    if not "%%f"=="%~nx0" (
        ren "%%f" "%%~nf"
    )
)
:: 仅去除特定类型文件的后缀(如.txt)
for %%f in (*.txt) do (
    ren "%%f" "%%~nf"
)

Linux/macOS (Bash)

# 去除当前目录下所有文件的后缀
for file in *; do
    if [ -f "$file" ]; then
        mv "$file" "${file%.*}"
    fi
done
# 去除特定类型文件的后缀(如.txt)
for file in *.txt; do
    [ -f "$file" ] && mv "$file" "${file%.*}"
done
# 简洁版本(使用rename命令)
rename 's/\.[^.]*$//' *
# 递归处理子文件夹
find . -type f -exec bash -c 'mv "$1" "${1%.*}"' _ {} \;

Python (跨平台)

import os
from pathlib import Path
# 去除当前目录下所有文件的后缀
def remove_suffixes(directory="."):
    for file in Path(directory).iterdir():
        if file.is_file():
            new_name = file.stem  # 去除后缀的文件名
            file.rename(file.parent / new_name)
# 仅去除特定类型文件的后缀
def remove_specific_suffix(directory=".", extension=".txt"):
    for file in Path(directory).glob(f"*{extension}"):
        if file.is_file():
            new_name = file.stem
            file.rename(file.parent / new_name)
# 递归处理
def remove_suffixes_recursive(directory="."):
    for file in Path(directory).rglob("*"):
        if file.is_file():
            new_name = file.stem
            file.rename(file.parent / new_name)
if __name__ == "__main__":
    remove_suffixes()

使用注意事项

  1. 备份文件:操作前建议先复制一份文件备份
  2. 区分大小写:Linux系统对大小写敏感,Windows不敏感
  3. 文件名冲突:如果有两个同名的文件(如a.txt和a.pdf),去除后缀后会发生冲突
  4. 特殊情况:Windows系统中,文件名末尾不能有空格和点号

安全用法示例

# Linux/macOS - 先预览变更
for file in *; do
    [ -f "$file" ] && echo "$file -> ${file%.*}"
done
# Windows PowerShell - 先预览变更
Get-ChildItem -File | ForEach-Object { Write-Host "$($_.Name) -> $($_.BaseName)" }

选择适合你系统的脚本,并在使用前先进行测试或预览。

抱歉,评论功能暂时关闭!