Question

I'm trying to copy some files from one directory to two other directories, using batch.

First i'm making 3 directories and after that, i want to copy the following files to backup1 and backup2. The files are named 010101.txt - 300101.txt (To backup1) and 010102.txt - 300102.txt (backup2).

mkdir backup1
mkdir backup2
mkdir backup3
copy 1.txt C:\User\Test\Backup1
copy 2.txt C:\User\Test\Backup2

I guess i have to use wildcard somehow, but if i write ?????1.txt and ?????2.txt i get an syntex error.

Was it helpful?

Solution

Try this out:

@echo off
setlocal enabledelayedexpansion

cd /d "C:\Temp\copytest"
set "b1=C:\Temp\Backup1"
set "b2=C:\Temp\Backup2"
for /l %%a in (1,1,300102) do (
  set num=%%a
  if %%a GTR 10000 if %%a LSS 100000 set num=0%%a
  if !num:~-1! EQU 1 (
     if exist !num!.txt echo copy !num!.txt %b1%
  ) ELSE (
     if !num:~-1! EQU 2 (
       if exist !num!.txt echo copy !num!.txt %b2%
     )
  )
)

Change paths where applicable. Remove the echos after verifying the output is correct to do the actual copy.

Edit: Simpler way

Copy *1.txt "C:\User\Test\Backup1"
Copy *2.txt "C:\User\Test\Backup2"

OTHER TIPS

@ECHO OFF
SETLOCAL
SET "sourcedir=."
FOR %%b IN (1 2) DO (
 FOR /f "delims=" %%a IN (
  'dir /b /a-d "%sourcedir%\*.txt" ^| find /i "%%b.txt" '
   ) DO (
  XCOPY "%sourcedir%\%%a" "c:\user\test\backup%%b\" >nul
 )
)
GOTO :EOF

I've assumed you want all files in the directory that contain 1.txt to be copied to ...\backup1 and those that contain 2.txt to ...\backup2.

I used my current directory for testing. You'd need to change the value assigned to 'sourcedir' to suit yourself.

Note that the xcopy will create the destination directory if necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top