【问题标题】:Replace Underscores with Spaces in Filename of Single File via Batch通过批处理将单个文件的文件名中的下划线替换为空格
【发布时间】:2016-11-02 21:31:33
【问题描述】:

我发现了以下帖子: Batch File to replace underscores with spaces in a filename

这似乎可行,但是当您将文件拖到批处理文件上时,它会处理文件夹中的所有文件。

@echo off
setlocal enabledelayedexpansion
for %%a in (*_*) do (
  set file=%%a
  ren "!file!" "!file:_= !"
)

有没有办法编辑它,这样我就可以只将要重命名的文件拖到批处理文件上,然后重命名该文件?

我还发现这个链接非常适合重命名一个文件,但它与我想要做的相反: Renaming files with spaces and dots in the filename

@ECHO OFF &setlocal

FOR %%f IN (%*) DO (
set "oldname=%%~ff"
set "oldfname=%%~nf"
set "extension=%%~xf"
setlocal enabledelayedexpansion
set "filename=!oldfname:.=_!"
set "filename=!filename: =_!"
if not "!filename!"=="!oldfname!" RENAME "!oldname!" "!filename!!extension!"
endlocal
)

谢谢!

-汤姆·K。

【问题讨论】:

  • 如果将文件拖到批处理文件上,它将成为批处理文件的参数。批处理文件将其视为%1。因此,首先将%1 设置为环境变量,然后使用该变量进行字符串替换。
  • 既然您有一段工作代码,那么根据您的需要调整子字符串替换应该不会太难,您不觉得吗?要强制脚本只关心第一个通过的项目,只需将 %* 替换为 "%~1"...
  • 非常感谢!我一直在尝试
  • ...尝试使用 %1 但我不知道在批处理中的何处使用它。我也尝试过编辑 _!部分,但我现在意识到我没有看到 set "filename=!filename: =!" 中的空间所以我把它改成了:set "filename=!filename:_= !"一切都很完美!

标签: windows batch-file drag-and-drop file-rename


【解决方案1】:

您可能只需要一个类似以下内容的结构:

@Echo Off
Set file=%~nx1
If Not Defined file Exit/B
Set "locn=%~dp1"
If Not Exist "%locn%%file%" Exit/B
If Not Exist "%locn%%file:_= %" (Ren "%locn%%file%" "%locn%%file:_= %")

【讨论】:

  • 请记住,拖放时完整路径是文件名的一部分。您只想重命名文件名。您可能会不小心更改文件路径中的字符。使用 nx 设置文件并使用 %1 重命名。
猜你喜欢
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 2016-09-05
  • 2014-11-27
  • 2018-01-28
  • 2014-11-30
  • 1970-01-01
相关资源
最近更新 更多