Qualquer método / comando / software para executar um movimento de arquivo relativo?

0

Vou explicar o que estou tentando fazer.

De um projeto com milhares de arquivos, queremos remover muitos deles correspondentes a um padrão, mas queremos armazenar um backup. Estamos procurando um método para realizar uma operação de movimentação que manterá a estrutura de pastas relativa no destino.

Quero dizer, se tivermos:

D:\matchingfile1.txt
D:\matchingfile2.txt
D:\nonmatchingfile1.txt
D:\nonmatchingfile2.txt
D:\foofolder\matchingfile1.txt
D:\foofolder\matchingfile2.txt
D:\foofolder\nonmatchingfile1.txt
D:\foofolder\nonmatchingfile2.txt
D:\barfolder\sub\matchingfile1.txt
D:\barfolder\sub\matchingfile2.txt
D:\barfolder\sub\nonmatchingfile1.txt
D:\barfolder\sub\nonmatchingfile2.txt

Queremos movê-lo para D: \ BACKUP \ 20130527 \ com este resultado:

D:\_BACKUP130527\matchingfile1.txt
D:\_BACKUP130527\matchingfile2.txt
D:\_BACKUP130527\foofolder\matchingfile1.txt
D:\_BACKUP130527\foofolder\matchingfile2.txt
D:\_BACKUP130527\barfolder\sub\matchingfile1.txt
D:\_BACKUP130527\barfolder\sub\matchingfile2.txt

NOTA 1: Arquivos para mover não são aqueles com o nome "matchingfile" , este é apenas um exemplo ilustrativo. O que atualmente extraímos é uma lista de todos os caminhos completos dos nossos arquivos de destino (texto simples), então isso tem que ser a entrada do método / comando / programa.

NOTA2: o nível do diretório pode ser qualquer.

O trabalho está no sistema operacional Windows 7.

Muito obrigado antecipadamente.

    
por Áxel Costas Pena 27.05.2013 / 11:10

5 respostas

2

Eu dei uma olhada agora quando cheguei em casa e isso está funcionando para mim

setlocal EnableDelayedExpansion

IF [%1]==[] (set txtpath=%CD%\list.txt) else (set txtpath=%1)
set projectfolder="D:\"
set savelocation="D:\_Backup"

cd /d %projectfolder%
set lenght=%CD%
set i=-1
set n=0
:nextChar
    set /A i+=1
    set c=!lenght:~%i%,1!
    set /A n+=1
    if "!c!" == "" goto endLine 
    goto nextChar

:endLine
for /f "tokens=*" %%A in (!txtpath!) do call :filecheck "%%A"
goto :eof

:filecheck
set folder=%~pd1%
set location="!folder:~%n%!"
if not exist %savelocation%\%location% mkdir %savelocation%\%location%
copy %1 %savelocation%\%location% && del /q %1
goto :eof
endlocal

Refiz o script para refletir que você queria um arquivo * .txt como entrada para os caminhos de arquivos, isso funciona para mim, você precisa definir "projectfolder", "savelocation", "txtpath" mas depois disso o script pode ser executado de qualquer lugar, e faz o que você quer. (você pode arrastar e soltar um arquivo txt nele depois de configurar a pasta do projeto / savelocation)

Ele recria a estrutura de pastas para todos os arquivos no arquivo .txt, em qualquer local da unidade (ou outra unidade para esse fim), copia os arquivos e os exclui da pasta original.

    
por 27.05.2013 / 17:32
1

Bem, isso seria um simples comando xcopy, mas você tem a pasta _backup em D: então atravessar a unidade D: pegaria a pasta _backup

Você pode tornar o _backup oculto para poder

xcopy d:\matchingile?.txt d:\_backup\matchingfile?.txt /s

    
por 27.05.2013 / 11:26
1
Pessoalmente, comecei a aprender alguns scripts de powershell, o que seria ótimo para um trabalho como esse. Basta salvar o código em um arquivo .ps1 e certificar-se de ativar a execução de scripts do PowerShell (Set-ExecutionPolicy RemoteSigned). Dessa forma, você tem uma ferramenta de filtragem mais poderosa, usando expressões regulares, em vez de apenas curingas. O script também poderia ser modificado para aceitar uma lista de arquivos de um arquivo de texto.

# Variables
$backupFolder="D:\_BACKUP130527";
$folderTobeBackedUp="D:\";
$overwrite=$True;
$filter="filenameToBeMatched";

function recurseDir($dir)
{
    $dirs=$(get-childitem "$($dir.FullName)");

    foreach( $f in $dirs)
    {
        if( $f.PSisContainer )
        {
            recurseDir $f;
        }    
        elseif($f.Name -imatch "$filter")
        {
            copyFile $f;
        }
    }
}

function copyFile($f)
{
    $newFile=$($f.FullName).Replace($folderTobeBackedUp, $backupFolder);
    $parent="$(Split-Path $newFile -Parent)";
    if( -not (test-path $parent))
    {
        new-item -Path $parent -type "directory";
    }
    try
    {
        $f.CopyTo("$newFile", $overwrite);
        (rmdir -Path $f.FullName -Force);
    }
    catch
    {
        Write-Host $_.Exception.ToString();
    }   
}

$folders=$(get-childitem "$folderTobeBackedUp");
foreach($f in $folders)
{
    if( $f.Name -imatch "_BACKUP" )
    {
        ; # Do nothing.
    }
    elseif( $f.PSisContainer )
    {
        recurseDir $f;
    }
    elseif($f.Name -imatch "$filter")
    {
        copyFile $f;
    }
}
    
por 27.05.2013 / 23:42
-1

Seria uma opção instalar ferramentas de ferramentas unix ou uma linguagem de script (como o perl)?

Essencialmente, se você tem alguma linguagem que possa ler um arquivo, você pode ler linha por linha em uma variável e executar

Estou apenas esboçando isso aqui no perl (com certeza precisará de algum refinamento):

while ( <NAMESFILE> ) {  # for all lines until EOF
   $file= $_;
   system("xcopy $file d:\backup\$file");
   system("del $file");
}

O xcopy neste caso criará o caminho completo e o del então removerá o original.

    
por 27.05.2013 / 14:49
-1

O XCOPY faz o trabalho que você precisa. Pode ser usado em um trabalho em lotes assim:

xcopy "C:\FolderName\*.*" "D:\FolderName\*.*" /D /E /V /C /I /F /H /R /K /Y /Z

Aqui está a sintaxe completa, incluindo os significados dos switches:

C:\>xcopy /?
Copies files and directory trees.

XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W]
                           [/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U]
                           [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z]
                           [/EXCLUDE:file1[+file2][+file3]...]

  source       Specifies the file(s) to copy.
  destination  Specifies the location and/or name of new files.
  /A           Copies only files with the archive attribute set,
               doesn't change the attribute.
  /M           Copies only files with the archive attribute set,
               turns off the archive attribute.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /EXCLUDE:file1[+file2][+file3]...
               Specifies a list of files containing strings.  Each string
               should be in a separate line in the files.  When any of the
               strings match any part of the absolute path of the file to be
               copied, that file will be excluded from being copied.  For
               example, specifying a string like \obj\ or .obj will exclude
               all files underneath the directory obj or all files with the
               .obj extension respectively.
  /P           Prompts you before creating each destination file.
  /S           Copies directories and subdirectories except empty ones.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /V           Verifies each new file.
  /W           Prompts you to press a key before copying.
  /C           Continues copying even if errors occur.
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Q           Does not display file names while copying.
  /F           Displays full source and destination file names while copying.
  /L           Displays files that would be copied.
  /G           Allows the copying of encrypted files to destination that does
               not support encryption.
  /H           Copies hidden and system files also.
  /R           Overwrites read-only files.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
               empty directories and subdirectories.
  /U           Copies only files that already exist in destination.
  /K           Copies attributes. Normal Xcopy will reset read-only attributes.
  /N           Copies using the generated short names.
  /O           Copies file ownership and ACL information.
  /X           Copies file audit settings (implies /O).
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.
  /-Y          Causes prompting to confirm you want to overwrite an
               existing destination file.
  /Z           Copies networked files in restartable mode.

The switch /Y may be preset in the COPYCMD environment variable.
This may be overridden with /-Y on the command line.
    
por 27.05.2013 / 18:38