Selecione aleatoriamente Arquivo, Renomear, Mover para um novo diretório

1

Temos um diretório carregado com mais de 40 arquivos com nomes de arquivos diferentes. Todos começam com a mesma estrutura de nome de arquivo, mas uma data é anexada ao final.

Exemplo:

FILE.txt.01012013
FILE.txt.01022013
FILE.txt.01032013

Eu preciso criar um arquivo em lote que faça algumas coisas complexas e algumas não tão complexas:

  1. selecione apenas um arquivo.
  2. Renomeie esse arquivo para outro nome. (Exemplo: TEST.txt) Nota: O nome do arquivo renomeado sempre será TEST.txt)
  3. Mover o arquivo renomeado de seu diretório atual para um novo diretório.
  4. 15 minutos depois ... comece com o passo 1 novamente. (Nota: isso precisa continue a rodar até que não haja mais arquivos no original diretório.)

O que eu tentei: Meu nível de habilidade em arquivos em lote é muito básico e, portanto, tenho tentado pesquisar na Web por sugestões. Eu posso encontrar o código para renomear um arquivo (mas você tem que indicar o nome do arquivo original). Eu posso encontrar código para encontrar um arquivo usando um * no nome do arquivo, mas eu acho que seleciona todos os arquivos no diretório. Eu preciso que isso aconteça com um arquivo de cada vez, e a cada 15 minutos. Quando um arquivo é renomeado e movido para o novo diretório ... Existe um processo de observador de arquivos que pega esse arquivo (neste exemplo, TEST.txt) e ingere os dados. Depois que os dados são ingeridos, o arquivo é excluído. Isso significa que quando o próximo arquivo for renomeado para TEST.txt e movido para o diretório, não haverá motivo para sobrescrever o arquivo anterior.

    
por JP Hooks 08.04.2013 / 20:32

3 respostas

0

Parece o que você quer, mas você precisa preencher as lacunas.

set count=0
for /f %%i in (file_path\*.*) do set /a count+=1
set test=%count%
:loop
if %test% neq %count% timeout /nobreak 900 >nul
set /a num=%random% %% %count% + 1
set /a count-=1
if %count% leq 0 goto end
for /f "skip=%num%" %%i in (file_path\*.*) do (
    ren %%i TEST.txt
    move TEST.txt file_path\
    goto loop
)
:end

O que faz:

  1. Descubra quantos arquivos em uma pasta (que você precisa alterar).
  2. Faça um número aleatório com o max sendo a quantidade de arquivos na pasta.
  3. Retire um do número máximo para a próxima vez.
  4. Ignora uma quantidade aleatória de arquivos (designados pelo número aleatório) e escolha o próximo.
  5. Renomeie o arquivo para TEXT.txt e mova-o para file_path \ (que você precisa alterar).
  6. Aguarde 15 minutos (900 segundos).

Espero que ajude.

Note que você precisa alterar ** file_path ** para os arquivos apropriados.

    
por 08.04.2013 / 23:52
0

Tente isso, ele faz todas as coisas que você pediu:

@echo off&setlocal enabledelayedexpansion
set "startfolder=folder1"
set "targetfolder=folder2"

cd /d "%startfolder%"
:randomstart
set /a filecnt=0
for %%i in (*) do set /a filecnt+=1
if %filecnt% equ 0 echo(no file found in %Startfolder%&goto:eof
set /a rd=(%random%%%%filecnt%)+1
set /a cnt=0
for %%i in (*) do set /a cnt+=1&if "!cnt!" equ "%rd%" set "randomfile=%%~i"
echo "%randomfile%"
move "%randomfile%" "%targetfolder%\test.txt"
ping -n 900 localhost >nul
goto:randomstart
    
por 09.04.2013 / 00:28
-1

Aqui está um script em lote simples para processar os arquivos:

@echo off

rem     set your file-match pattern here. Could be *.* for all files, or whatever you wish.
set "zzmatchpattern=FILE.txt.*"

rem     set filename for renamed files
set "zzfinalname=TEST.txt"

rem     set source folder here
set "zzsourcepath=C:\source\"

rem     set destination folder here
set "zzdestpath=C:\dest\"

rem     set your loop delay here
set "zzdelayminutes=15"

rem     **********************************
rem     might be good to add some error checking here
rem     **********************************


:start
rem:start
set /a zzdelayseconds=zzdelayminutes*60


:restart
rem:restart

for %%f in ("%zzsourcepath%%zzmatchpattern%") do call :work "%%~f"

timeout /t %zzdelayseconds%
goto :restart


:work
rem:work

set "zz_w1=%~1"
echo.
echo Renaming file "%zz_w1%" to "%zzfinalname%"
ren "%zz_w1%" "%zzfinalname%">nul 2>&1

echo Moving file: "%zzsourcepath%%zzfinalname%" to "%zzdestpath%"
move "%zzsourcepath%%zzfinalname%" "%zzdestpath%">nul 2>&1

timeout /t %zzdelayseconds%

rem     Go get next file, if any.
goto :EOF



Se você deseja uma solução mais completa, o script em lote abaixo inclui:

  • Validação razoavelmente completa (verificação de erros) dos valores de entrada.
  • Com a modificação simples, os valores podem ser inseridos com segurança a partir da linha de comando.
  • Inicialmente, verifica se o arquivo de destino existente está presente e aguarda que o processo externo remova o arquivo.
  • Verifica e informa sobre operações de renomeação e movimentação com falha.
  • Retomar após os arquivos de processos de encerramento / falha renomeados, mas não movidos.
  • Permite atraso (opcional) solicitado (Choice.exe) permitindo "Continuar agora" e "Sair".


@echo off

rem     set your file-match pattern here. Could be *.* for all files, or whatever you wish.
set "zzmatchpattern=FILE.txt.*"

rem     set filename for renamed files
set "zzfinalname=TEST.txt"

rem     set source folder here
set "zzsourcepath=C:\source"

rem     set destination folder here
set "zzdestpath=C:\dest"

rem     set your loop delay here
set "zzdelayminutes=15"

rem     select  Prompted-delay, or simple Timeout-delay. P=Prompted, otherwise simple Timeout
rem     For Prompted-delay "Choice.exe" must be present on the computer.
set "zzdelaytype=T"


rem     **********************************
rem     error checking
rem     **********************************


:checksourcepath
rem:checksourcepath

rem     insure source path is valid (exists), and has trailing slash
if "%zzsourcepath%."=="." goto :sourcepatherror
set zzt1=%zzsourcepath:~-1,1%
if not "%zzt1%."=="\." set "zzsourcepath=%zzsourcepath%\"
if not exist "%zzsourcepath%*.*" goto :sourcepatherror
goto :checkdestpath


:sourcepatherror
rem:sourcepatherror

echo.
echo Error processing source path: [%zzsourcepath%].
echo.
call :cleanexit
exit /b 1


:checkdestpath
rem:checkdestpath

rem     insure dest path is valid (exists), and has trailing slash
if "%zzdestpath%."=="." goto :destpatherror
set zzt1=%zzdestpath:~-1,1%
if not "%zzt1%."=="\." set "zzdestpath=%zzdestpath%\"
if not exist "%zzdestpath%*.*" goto :createdestpath
goto :checkname


:createdestpath
rem:createdestpath

md "%zzdestpath%" >nul 2>&1
if not exist "%zzdestpath%*.*" goto :destpatherror
goto :checkname


:destpatherror
rem:destpatherror

echo.
echo Error processing destination path: [%zzdestpath%].
echo.
call :cleanexit
exit /b 2


:checkname
rem:checkname

if "%zzfinalname%."=="." goto :nameerror
goto :checkdelayminutes


:nameerror
rem:nameerror

echo.
echo Error: Rename target filename cannot be empty.
echo.
call :cleanexit
exit /b 3


:checkdelayminutes
rem:checkdelayminutes

set zzt1=0
set zzt2=1
set /a zzt1=zzt2*zzdelayminutes
if "%zzt1%."=="." goto :minute1serror
if %zzt1% LEQ 0 goto :minutes1error
if %zzt1% GEQ 1441 goto :minutes2error
goto :checkpattern


:minutes1error
rem:minutes1error

echo.
echo Error: Minutes must be a number greater than 0.
echo.
call :cleanexit
exit /b 4


:minutes2error
rem:minutes2error

echo.
echo Error: Minutes must be a number not greater than 1440 (1 day).
echo.
call :cleanexit
exit /b 5


:checkpattern
rem:checkpattern

rem     pattern must have at least 1 "*"
if "%zzmatchpattern%."=="." goto :patternerror
echo "%zzmatchpattern%"|find "*">nul
if %errorlevel% EQU 0 goto :start
rem goto :patternerror


:patternerror
rem:patternerror

echo.
echo Error: Pattern cannot be empty, and must contain at least 1 "*".
echo.
call :cleanexit
exit /b 6


:start
rem:start
set /a zzdelayseconds=zzdelayminutes*60
set /a zzpartialdelay=zzdelayseconds/3
set zzexiting=0


:restart
rem:restart

rem     if destination file already exists, wait a bit more

if not exist "%zzdestpath%%zzfinalname%" goto:checkaborted

call :waitexternal
if %zzexiting% NEQ 0 exit /b %zzexiting%
goto :restart


:checkaborted
rem:checkaborted

if not exist "%zzsourcepath%%zzfinalname%" goto :work1
echo.
echo Completing previously started file move.
echo Moving file: "%zzsourcepath%%zzfinalname%" to "%zzdestpath%"
move "%zzsourcepath%%zzfinalname%" "%zzdestpath%">nul 2>&1
goto :restart


:work1
rem:work1

set zzdelayflag=1
set zzsuccess=0
for %%f in ("%zzsourcepath%%zzmatchpattern%") do call :work2 "%%~f"

if %zzexiting% NEQ 0 exit /b %zzexiting%

echo %zzsuccess% file(s) processed.

if %zzdelayflag% EQU 0 goto :checksuccess
call :dodelay %zzdelayseconds%
if %zzexiting% NEQ 0 exit /b %zzexiting%
goto :restart


:checksuccess
rem:checksuccess

if %zzsuccess% NEQ 0 goto :restart

echo.
echo Failed to rename all existing files, exiting.
call :cleanexit
set zzexiting=7
exit /b %zzexiting%
goto :EOF


:work2
rem:work2

if %zzexiting% NEQ 0 exit /b %zzexiting%

set "zz_w1=%~1"
set zzdelayflag=0
echo.
echo Renaming file "%zz_w1%" to "%zzfinalname%"
ren "%zz_w1%" "%zzfinalname%">nul 2>&1
if exist "%zz_w1%" goto :renameerror
if not exist "%zzsourcepath%%zzfinalname%" goto :renameerror
goto :movefinalfile


:renameerror
rem:renameerror

echo Error: Failed to rename file "%zz_w1%" to "%zzfinalname%"
echo.

rem     Rename failed, skip it and get next file (immediately), if any.
goto :EOF


:movefinalfile
rem:movefinalfile

rem Rename success, move the file

if not exist "%zzdestpath%%zzfinalname%" goto :domove

call :waitexternal
if %zzexiting% NEQ 0 exit /b %zzexiting%
goto :movefinalfile


:domove
rem:domove

echo Moving file: "%zzsourcepath%%zzfinalname%" to "%zzdestpath%"
move "%zzsourcepath%%zzfinalname%" "%zzdestpath%">nul 2>&1
if exist "%zzsourcepath%%zzfinalname%" goto :moveerror
goto :movecomplete


:moveerror
rem:moveerror

echo Error: Failed to move file "%zz_w1%" to "%zzdestpath%%zzfinalname%"

rem     Move failed, restore (un-rename) file and skip it and get next file (immediately), if any.

for %%g in ("%zz_w1%") do set "zzt1=%%~nxg"
echo Restore file: "%zzsourcepath%%zzfinalname%" to "%zzt1%"
ren "%zzsourcepath%%zzfinalname%" "%zzt1%">nul 2>&1
echo.

goto :EOF


:movecomplete
rem:movecomplete

set /a zzsuccess+=1
call :dodelay %zzdelayseconds%
if %zzexiting% NEQ 0 exit /b %zzexiting%
rem echo.

rem     Go get next file, if any.
goto :EOF


:dodelay
rem:dodelay

set zztime=%1

if /I "%zzdelaytype%."=="P." goto :dopauseddelay

echo.
timeout /t %zztime%
goto :EOF


:dopauseddelay
rem:dopauseddelay

echo.
echo Waiting (%zztime% seconds) to process next file... You can wait to 
echo continue after delay or Q(uit) or C(ontinue) now.
choice /c cq /n /t %zztime% /d c /m "Press Q(uit) or C(ontinue now) or No Action (wait) to continue after delay. "
if %errorlevel% EQU 1 goto :EOF

echo.
echo User selected Q(uit), exiting.
call :cleanexit
set zzexiting=254
exit /b %zzexiting%
goto :EOF


:waitexternal
rem:waitexternal

echo.
echo Waiting for externl process...
call :dodelay %zzpartialdelay%
if %zzexiting% NEQ 0 exit /b %zzexiting%

goto :EOF


:cleanexit
rem:cleanexit

set "zzdelayflag="
set "zzdelayminutes="
set "zzdelayseconds="
set "zzdelaytype="
set "zzdestpath="
set "zzexiting="
set "zzfinalname="
set "zzmatchpattern="
set "zzpartialdelay="
set "zzsourcepath="
set "zzsuccess="
set "zzt1="
set "zzt2="
set "zztime="
set "zz_w1="

goto :EOF

Se você precisar de algo modificado ou explicado, é só me avisar.

    
por 10.04.2013 / 02:12

Tags