1

I've found the following post: Batch File to replace underscores with spaces in a filename

This seems to work but when you drag a file onto the batch file, it processes all of the files in the folder.

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

Is there a way to edit this so I can just drag just the file I want to rename onto the batch file and just have that file renamed?

I also found this link that works great for just renaming one file, but it does the opposite of what I'm trying to do: 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
)

Thank you!

-Thom K.

Community
  • 1
  • 1
ThomK
  • 35
  • 1
  • 4
  • If you drag a file onto a batch file it becomes an argument to the batch file. The batch file will see it as `%1`. So set `%1` to an environmental variable first and then use string substitution with that variable. – Squashman Nov 02 '16 at 22:35
  • Since you have a working piece of code, it should not be too difficult to adapt the sub-string replacements to your needs, don't you think? To force the script to care about the firstly passed item only, simply replace `%*` by `"%~1"`... – aschipfl Nov 02 '16 at 23:05
  • Thank you very much! I had been trying to – ThomK Nov 03 '16 at 13:10
  • ...trying to use the %1 but I couldn't figure out where to use it in the batch. I had also tried editing the __! portions but I now realize I wasn't seeing the space in set "filename=!filename: =_!" So I changed it to: set "filename=!filename:_= !" And everything works perfectly! – ThomK Nov 03 '16 at 13:16

1 Answers1

0

You probably just need a structure something along these lines:

@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:_= %")
Compo
  • 36,585
  • 5
  • 27
  • 39
  • 2
    Remember that the full path is part of the file name when you drag and drop. You just want to rename the file name. You may accidentally change characters in the file path. Set file using nx and use %1 with the rename. – Squashman Nov 02 '16 at 22:58