2

I am trying to replace underscores in some file names with spaces, for example:

this_is_a_file.pdf

becomes:

this is a file.pdf

In Windows using a batch file.

I have found a similar question, but it replaces spaces with nothing: How to remove spaces from file names (in bulk)

Can it be easily translated to do what I want?

Community
  • 1
  • 1
Carolined
  • 33
  • 1
  • 1
  • 5

2 Answers2

7

Use %file:_= % to represent %file% with underscores replaced with spaces. Unfortunately this won't work on a for variable so if you're looping over files you have to use an intermediate variable.

@echo off
setlocal enabledelayedexpansion
for %%a in (*_*) do (
  set file=%%a
  ren "!file!" "!file:_= !"
)
Neil
  • 54,642
  • 8
  • 60
  • 72
  • that looks like it would work but I would quote the set command like so: SET "file=%%a" – djangofan Jan 17 '13 at 21:06
  • @djangofan Actually I tried it with spaces and ampersands and it didn't seem to need quotes. (But `"!file!"` did!) – Neil Jan 17 '13 at 21:38
  • Yeah, i always quote them "just to be safe" with vars that have spaces in them especially. Note: if you understand how the '~' char works in DOS, then there are some exceptions that work fine without. For example what if the above script tries to rename a file called "my_file named.txt" ? – djangofan Jan 17 '13 at 23:32
  • @djangofan It seems to want to rename it to `my file named.txt` (I actually used echo rather than ren for testing). – Neil Jan 18 '13 at 00:10
  • 1
    Thanks so much everyone! The answer was so simple! Can anyone recommend some good resources for batch scripting? – Carolined Jan 18 '13 at 05:38
1

Open the folder containing all the files to be renamed in Windows File Explorer, please be sure you are in the correct folder.

In the Address bar, type powershell and press Enter !

That should open PowerShell in that folder, check in the PowerShell window that you are in that folder !

Paste this into PowerShell and press Enter:

get-childitem . | foreach { rename-item $_ $_.Name.Replace("__", " ") }

That command will replace all underscores with a space in all file names in that folder.

Inside the first quote replace the underscore “_” with anything you want to replace and in the second quote inside the bracket put the text you want to replace it with. like with space in current scenario.

immu
  • 380
  • 1
  • 3
  • 8