Removing all characters in all file names in a folder up to the first space

72 Views Asked by At

I’m trying to write a .bat script to rename every file in a folder by removing all characters in all the file names up to the first space. I.e.:

ABC defghij -> defghij

And I need to automate this for all files in the folder. Is there a way to do this?

This is what I tried:

For %y in (directory) do (for /f “tokens=1,*” %%A in %y do ren %y” “%%B”)
2

There are 2 best solutions below

0
Magoo On
@ECHO OFF
SETLOCAL
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files\t w o"
FOR /f "delims=" %%y IN ('dir /b /a-d "%sourcedir%\* *"') DO (
 FOR /f "tokens=1*delims= " %%b IN ("%%y") DO (
  IF EXIST "%sourcedir%\%%c" (ECHO Cannot RENAME "%%y" to "%%c" - already exists) ELSE (
    ECHO REN "%sourcedir%\%%y" "%%c"
  )
 )
)

GOTO :EOF

Always verify against a test directory before applying to real data.

Notes

  • Your code has unbalanced quotes.
  • Your code has "smart quotes" - plain quotes are required
  • %y is correct from the command prompt, but metavariables like %%y need a double % in a batch file.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.

Fairly simple process - process a directory list matching the filemask of filenames only, tokenise as attempted, test whether rename is possible, report if it is not & rename if it is.

0
phuclv On

Use PowerShell instead, it's much easier. The simplest method involves a regex replace

ls | ren -Ne { $_.Name -replace "^.+? " } -wi
# or
ls | ren -Ne { $_.Name -replace ".+? (.*)", '$1' } -wi

or the full command

Get-ChildItem -Filter "* *" | Rename-Item -NewName { $_.Name -replace "^.+? " } -WhatIf
# or
Get-ChildItem -Filter "* *" | Rename-Item -NewName { $_.Name -replace ".+? (.*)", '$1' } -WhatIf

-WhatIf/-wi is for dry running, remove it to do real renaming

"^.+? " matches the first "word" and the next space after it and remove, whereas ".+? (.*)" captures the rest of the string and replace with what was captured