S
Items 1. a Five.:I've already researched and I have a basic notion but I'd like to know if anyone would know how to clarify what this expression does and how it does.Items 6. a 9.:...copy latest files from one directory to another. But besides being the latest (creation date) I have other conditions for copying:Start with "Financial Report"Files with the same name in different formats, one in .PDF another in .XLSX.Items 10. and 11. [move only 1 pair of files (1 .pdf + 1 .xlsx) by execution]:. but would like to copy only the latest pair. .1. Command execution Dir /B /A-D /O-D will result in listing items from the current folder, where this output will return only file names in a form "basic", a simple nome-de-arquivo.extensão and also not listing drive:\caminho\completo\para\nome-de-arquivo.extensãoDir // lista arquvivos e pastas no Diretorio atual
Dir /B // lista arquvivos e pastas na forma Básica, sem drive/caminho completo
Dir /A-D // lista arquivos apenas, por excluir os itens com Atributo de Diretório,
// observe que o "-" significa exclir o item, como em:
<b>/A-D</b> <==> <b>-D</b>iretórios <==> liste os itens, menos com <b>A</b>tributo <b>-D</b>iretórios
<b>/A-A</b> <==> <b>-A</b>rquivos <==> liste os itens, menos com <b>A</b>tributo <b>-A</b>rquivos
// observe que sem o "<b>-</b>" significa restringir/limitar ao item, como em:
<b>/AD</b> <==> <b>D</b>iretórios <==> liste os itens com <b>A</b>tributo <b>D</b>iretórios
<b>/AA</b> <==> <b>A</b>rquivos <==> liste os itens com <b>A</b>tributo <b>A</b>rquivos
Dir /O-D // lista arquivos em uma dada Ordem, nesse caso, por Data
// observe que o "-" aqui vai significar uma inversão da ordenação padrão:
<b>/OD</b> <==> <b>O</b>rdenar por <b>D</b>ata <==> liste do mais antigo para o mais recente/novo
<b>/O-D</b> <==> <b>O</b>rdenar por <b>D</b>ata <==> liste do mais recente/novo para o mais antigo
Dir/B/A-D/O-D // liste os nome de arquivos, exclindo os caminho/pastas, na ordem
// inversa, por data de modificação/data de criação (o que for mais recente).It turns out:> Dir /B /A-D /O-D
Q99999.txt
A99999.txt
Q99999.cmd
I99999.png2. The redirection made by the operator "|" from command output dir is treated in command Findstr, and this will result in a listing None of all rows resulting from the execution of the previous command, dir.Dir/B/A-D/O-D // liste arquivos na ordem inversa de data de modificação/criação (mais recente).
^ // o escaping para o uso do pipe "|", que é necessário no for/f ('^|')
| // redireciona a saída do comando anterior (Dir/B/A-D/O-D) para o Findstr
Findstr /N "^" // vai listar a saída obtida no comando anterior, Númerando todas as linhas.It turns out:> Dir /B /A-D /O-D | Findstr /N "^"
1:Q99999.txt
2:A99999.txt
3:Q99999.cmd
4:I99999.png3. The command For /F loop will create a loop to manipulate the actions resulting from the commands Dir/B..| Findstr.., capturing the output to make use of these by separating them in a predefined way, to meet in your delimiter (delims=:) defined, and the elements of the first occurrence (tokens= [1] ), and all () the elements of the second until the last occurrence (tokens=1-[] ).For any element/string that appears before the delimiter ":" (in the first occurrence of the delimiter), will be treated in the loop variable %%A, and all occurrences after the first occurrence, i.e. all occurrences/strings after %%A, will be treated in the loop variable %%B[ comando em loop] [ sáida em loop ]
Dir /B /A-D /O-D | Findstr /N "^" 1:Q99999.txt
<elemento %%A > [delimitador] <elemento(s) %%B>
1 : Q99999.txt
2 : A99999.txt
3 : Q99999.cmd
4 : I99999.png4. To explain the actions of this batch/batch code, I will withdraw (explaining), which is not necessary (or dispensable):@Echo off
Set "Xnewest=2" // define uma variavél atribuindo o numero 2 como valor
For /F "tokens=1* delims=:" %%A in (
'Dir /B /A-D /O-D ^| Findstr /N "^"'
) Do If %%A Leq %Xnewest% echo Move "%%B" "X:\Path\to\dest"
// 2 ecoe Move "%%B" "X:\Path\to\dest"
// 2 imprima na tela Move "%%B" "X:\Path\to\dest"For each item obtained from the outputs resulting from the command listing Dir..| Findstr, take %%A, which is the number that was assigned the current command output line Dir by Findstr, and if that line number is equal Equ or minor Lss (Equ [or] Lss > Leq), echo/print the command Move...The command echo Move.. will only enable a verification of the output of the processed loop, so that the author of the code, or the author of the question, has the possibility to check if the files where the command effectively occurs, satisfy the condition in the proposed goal, where it is noted that: [Dir] Liste arquivos dos mais recentes aos mais antigos e apenas nomes
[Findstr] Enumere as linhas dessa saída, na forma, "numero" + ":" + "nome.extensão"
[For + if (%%A ≦ 2)] Se número da linha é menor ou igual a 2, mova item %%B para drive:\pasta</code>Five. Components that must satisfy/observe to make this loop/bat effective:the bat is running in the same folder where the files are being "manipulated" in loopthe running bat, obligatoryly is older, or has its modification/edition prior to the loop files6. Considering the utility/application of the commented code, and making a suggestion to limit your action in just the two files .pdf, and .xlsx most recent, with the name starting in "Financial Report":@echo off && cd/d "z:\Pasta\de\Origem"
for %%i in (xlsx pdf)do for /F tokens^=1delims^=: %%A in (
'dir/b/a-d/o-d ."Relat?rio Financeiro.%%~i"^|findstr/n .
')do if %%~A leq 2 echo=move /y ".%%~B" "x:\Pasta\de\Destino."Same code/resulted in version with conventional layout:@echo off
cd /d "F:\Pasta\Origem"
for %%i in (xlsx,pdf) do (
for /F "tokens=1* delims=:" %%A in ('dir /b /a:-d /o:-d ."Relat?rio Financeiro*.%%~i" ^| findstr /n .') do (
if %%~A leq 2 echo=move /y ".%%~B" "X:\Pasta\de\Destino."
)
)7. In the suggestion proposed in the item 6., I'm replicating the command echo allowing the execution in tests/checks, after that, it is only to remove the echo= for effective file handling.@echo off && cd/d "z:\Pasta\de\Origem"
for %%i in (xlsx pdf)do for /F tokens^=1*^delims^=: %%A in (
'dir/b/a-d/o-d ."Relat?rio Financeiro*.%%~i"^|findstr/n .
')do if %%~A leq 2 move /y ".%%~B" "x:\Pasta\de\Destino."Same code/resulted in version with conventional layout:@echo off
cd /d "F:\Pasta\Origem"
for %%i in (xlsx,pdf) do (
for /F "tokens=1* delims=:" %%A in ('dir /b /a:-d /o:-d ."Relat?rio Financeiro*.%%~i" ^| findstr /n .') do (
if %%~A leq 2 move /y ".%%~B" "X:\Pasta\de\Destino."
)
)Eight. To move files with the same names and different extensions by applying the order by modification/creation date (which is latest), applying to the file .pdf and also mesmos_nome.xlsx:@echo off && cd/d "z:\Pasta\de\Origem"
for /F tokens^=1delims^=: %%A in ('dir/b/a-d/o-d/tc ."Relat?rio Financeiro.xlsx"^|findstr/n .
')do if %%~A leq 2 for %%i in (.pdf,%%~xB)do move /y ".%%~nB%%~i" "x:\Pasta\de\Destino."Same code/resulted in version with conventional layout:@echo off
cd /d "z:\Pasta\de\Origem"
for /f "tokens=1* delims=:" %%A in ('dir /b /a:-d /o:-d /t:c ."Relat?rio Financeiro*.xlsx" ^| findstr /n .') do (
if %%~A leq 2 for %%i in (.pdf,%%~xB) do move /y ".%%~nB%%~i" "x:\Pasta\de\Destino."
)9. To apply the results only in files where the listing is by creation date order (not modification), just add /TC@echo off && cd/d "z:\Pasta\de\Origem"
for /F tokens^=1delims^=: %%A in ('dir/b/a-d//o-d/tc ."Relat?rio Financeiro.xlsx"^|findstr/n .
')do if %%~A leq 2 for %%i in (.pdf,%%~xB)do move /y ".%%~nB%%~i" "x:\Pasta\de\Destino."Same code/resulted in version with conventional layout:@echo off
cd /d "z:\Pasta\de\Origem"
for /f "tokens=1* delims=:" %%A in ('dir /b /a:-d /t:c ."Relat?rio Financeiro*.xlsx" ^| findstr /n .') do (
if %%~A leq 2 for %%i in (.pdf,%%~xB) do move /y ".%%~nB%%~i" "x:\Pasta\de\Destino."
)10. To get the latest file, whether this is a .pdf or one .xlsx, and use the same name for (of the latest file) and move it in "par", (.xlsx + .pdf or .pdf + .xlsx) for another folder:@echo off && cd /d "z:\Pasta\de\Origem"
for /f tokens^=* %%i in (
'dir/b/a-d/o-d/tc ."Relat?rio Financeiro*.*"^|%AppDir%findstr.exe/eli ".pdf .xlsx"')do (
move /y ".%%~nxi" "x:\Pasta\de\Destino." && if /i "%%~xi" == ".xlsx" >nul (
move /y ".%%~ni.xlsx" "x:\Pasta\de\Destino." ) else >nul (
move /y ".%%~ni.pdf" "x:\Pasta\de\Destino.")
) & goto :eOfDir/B/A-D/O-D/TC // liste arquivos na ordem inversa de data (criação)
^ // o escaping para o uso do pipe "|", que é necessário no for/f ('^|')
| // redireciona a saída do comando anterior (Dir/B/A-D/O-D/T:C) para o Findstr
Findstr/ELI // obtem no comando anterior, arquivos que terminam (End) Literalmente Insensitivo
".pdf .xlsx" // obtem as linhas que terminarem Literalmente com ".pdf" ou ".xlsx" caso
// Lnsensitivo (independente de caixa alta ou baixa)
// observe que o <b>"\."</b> é diferente de <b>"."</b>, onde sem o uso do "escape" <b>\</b>, vai
// significar para o <b>Findstr "qualquer caratere"</b>, mas já o <b>\.</b> vai sinalizar
// <b>L</b>iteralmente "." o ponto, assim resultando nas extensões <b>"."+pdf e/ou ".xlsx"</b>
if /i // uso do if em condição de comparação de caso Iinsensitivo
"%%~xi"==".xlsx" // se a eXtensão ("%%~xi") do arquivo em loop for igual ".xlsx", ele move tambémm
// o arquivo com o mesmo Nome + eXtensão ".pdf" par a pasta de destino, caso o
// contrario aconteça, o arquivo ".pdf" é o mais velho dentro do loop, vai
// inverter a ação, movendo primeiro o .pdf, e depois o arquvo de mesmo nome .xlsx
Goto :eOf // como a primeiro laço/loop já foi excutado, o par também já foi movido, e
// entendendo que os outros arquivos do loop não são mais necessários, então
// aborta-se a execução do loop/processamento, movendo a execução do batch
// para o final do arquivo (Goto End Of File)11. Case in your files, the extension ".pdf" are always the latest, and you just need to set the action so that you base yourself on this extension to get the nomde of the "par" file in "xlsx", or the opposite, inverting ".pdf"/".xlsx", the arrow:@echo off
cd/d "z:\Pasta\de\Origem"
for /f tokens^=* %%i in ('
dir/b/a-d/o-d/tc ."Relat?rio Financeiro*.pdf"')do >nul (
move /y ".%%~ni.xlsx" "x:\Pasta\de\Destino."
move /y ".%%~nxi" "x:\Pasta\de\Destino."
goto :eOf
)Additional explanations about for /f, skip, tokens and delims: https://pt.stackoverflow.com/a/466209/131559 Some references for consultation/support in /English: https://ss64.com/nt/if.html https://ss64.com/nt/dir.html https://ss64.com/nt/move.html https://ss64.com/nt/for.html https://ss64.com/nt/for_f.html https://ss64.com/nt/cd.html https://www.robvanderwoude.com/redirection.php