1

I have filenames consisting of a number, a space and a name. For example, "023 filename1.txt".

I want to create a Batch script which renames such files. It needs to identify the sub-strings and remove everything before the space character. For example, "023 filename1.txt" would be renamed to "filename1.txt".

Please explain how to do this in a Batch file.

2
  • Do you want to rename the sample file to filename1.txt or filename.txt? Commented Jul 15, 2012 at 18:54
  • Thanks for the timely comment. I've edited above. Commented Jul 15, 2012 at 18:57

2 Answers 2

2
@echo off
setlocal EnableDelayedExpansion
for %%a in (*.txt) do (
   set newName=%%a
   ren "%%a" "!newName:* =!"
)

This part: "!newName:* =!" mean "take newName variable and replace from the beginning of its value until the space with nothing", that is, eliminate the beginning until the first space.

Sign up to request clarification or add additional context in comments.

Comments

1

This only echoes the commands it would execute. Remove the echo on the third line to actually do the rename.

@echo off
for %%F in (*.txt) do (
  for /F "tokens=1,*" %%I in ("%%F") do echo ren "%%F" "%%J"
)

The first for iterates over all the .txt files.

The second for splits each file name into the initial number and the rest using tokens=1,*. %I gets the number (which is ignored) and %J gets the new file name.

1 Comment

This can also remove multiple spaces between the number and the rest of the name, which may be even better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.