Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Baruch to replace space in file name with underscore.  (Read 2692 times)

0 Members and 1 Guest are viewing this topic.

Geek-9pm

    Topic Starter

    Mastermind
  • Geek After Dark
  • Thanked: 1026
    • Gekk9pm bnlog
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Baruch to replace space in file name with underscore.
« on: December 08, 2016, 09:48:28 PM »
Baruch to replace space in file name with underscore.
OK,I already did it.   :)
But I was wondering how you would do it.
Here is the problem.Some utilities s used for batch programming don't do well with spaces in file names. Unless you put quotes around everything.
For me,I would rather have underscores and forget about the nice way spaces look in file names. Just a personal quirk. So I renamed any file-name  with a space to have a underscore character instead.
The method took me about an hour while working with another problem.  But I only had 25 file names. It should not have taken that long. What would I doif ever  do  if I had 200 names with spaces?
So, my question is : How would you rename all files with space in the name to have only an underscore a dash instead?
Some sample names in a single directory::
Code: [Select]
My Dog and Cat.txt
New Phone .txt
NoSpaceHere.txt
west sunset.txt
Lost and found from back yard.txt
Anybody?  :)

strollin



    Adviser
  • Thanked: 84
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Guru
  • OS: Windows 10
Re: Baruch to replace space in file name with underscore.
« Reply #1 on: December 09, 2016, 06:34:13 AM »
You could do it with something like a Python script but are you asking for a batch file to do it?  What's a Baruch?  Might be a way in batch but it would be complicated.

Code: [Select]
import os
import string

path = r'.'

for name in os.listdir(path):
   if os.path.isfile(os.path.join(path, name)):
      if string.find(name, ' ') > 0 :
         fnm = name.split(' ')
         fname = '_'.join(fnm)
         os.rename(name, fname)

Geek-9pm

    Topic Starter

    Mastermind
  • Geek After Dark
  • Thanked: 1026
    • Gekk9pm bnlog
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Re: Baruch to replace space in file name with underscore.
« Reply #2 on: December 09, 2016, 10:48:26 AM »
Baruch?
Not sure what that was. I have lost my eye teeth, do I can not see what I say.

Thanks for the Python script. I will add that to my collection.

Salmon Trout

  • Guest
Re: Baruch to replace space in file name with underscore.
« Reply #3 on: December 10, 2016, 02:47:36 AM »
Very simple in batch.

Code: [Select]
@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%A in ('dir /b ^| find " "') do (
set oldname=%%A
set newname=!oldname: =_!
echo Renaming "!oldname!" to "!newname!"
ren "!oldname!" "!newname!"
)
echo Done
Pause