Search code examples
batch-filefile-rename

Copy and Rename Files with batch file


I have thousands of text files formatted something similar to abcdefgh_20140430120000.txt

I would like to copy those from one folder to another folder like

xcopy "Y:\FolderA" "C:\FolderB" 

However, I want to remove the time portion in the file name so that the text file would look like abcdefgh_20140430.txt

Can anyone help me with code to do so?


Solution

  • Launch this in the folder: it should copy them as you wish and remove the last 6 characters of the filename.

    Filenames with ! in them will generate an error.

    @echo off
    setlocal enabledelayedexpansion
    for /f "delims=" %%a in ('dir *.txt /b /a-d ') do (
        set "name=%%~na"
        copy "%%a" "C:\FolderB\!name:~0,-6!%%~xa" 
    )