Reputation: 13
Ok,
I have multiple text files that will be coming into a folder that I am processing into a single output file. The batch will run every few hours.
for %%f in (*.txt) do type "%%f" >> ESOComplete\ESOInput.txt
This will copy all text from text files to one single text file in another subfolder.
From there I need one to move all files (Example 510002.txt) to a subfolder called ESOMoved. Leaving the root folder empty so next time the batch runs it doesn't add the same data to the ESOInput.txt
Now, I need the batch file that moves the orignal data from the root to not overwrite, so if files already exists I want it to rename it (From 510002.txt to 5100022.txt)
In the end it should be 1. Move all text from all .txt documents to one output file. (Which is already done) 2. Move all .txt documents to subfolder called ESOMoved, unless that specific document already exists, in which case rename, and then move.
Upvotes: 1
Views: 982
Reputation:
EDIT
If the file with the appended 2
already exists the number is increased until it is free.
@Echo off
:: Start in base folder
PushD "Q:\Test\2017\07\22"
for %%f in (??????.txt) do (
type "%%f" >> "ESOComplete\ESOInput.txt"
If Not Exist "ESOMoved\%%f" (
Move "%%f" "ESOMoved\"
) Else (
Set Num=2
Call :Move "%%f"
)
)
PopD
Goto :Eof
:Move
Set "NewName=ESOMoved\%~n1%Num%%~x1"
If Not Exist "%NewName%" (
Echo Move %1 "%NewName%"
Move %1 "%NewName%" >Nul 2>&1
Exit /B 0
)
Set /A Num+=1
Goto :Move
Upvotes: 1
Reputation: 16226
The trick to this is devising a renaming scheme. The code below appends "-N" to the file basename to create a unique file it will keep incrementing N until if finds a filename that does not exist.
Save this file as esomover.ps1
.
$files = Get-ChildItem -Path 'C:/src/t/ESO/' -File -Filter 'file*.txt'
$sum_file = 'C:/src/t/ESO/ESOComplete/ESOInput.txt'
$arch_dir = 'C:/src/t/ESO/ESOArchive'
if (-not (Test-Path -Path $sum_file)) { New-Item -Path $sum_file -ItemType File }
foreach ($file in $files) {
Add-Content -Path $sum_file -Value (Get-Content $file.FullName) -Encoding Ascii
if (-not (Test-Path "$($arch_dir)/$($file.Name)")) {
Move-item $file.FullName $arch_dir
} else {
$i = 0
$nfn = ''
do {
$nfn = "$($file.BaseName)-$($i.ToString()).txt"
$i++
} while (Test-Path -Path "$($arch_dir)/$($nfn)")
Move-Item $file.FullName "$($arch_dir)/$($nfn)"
}
}
Run this script from a cmd.exe shell or .bat file using:
powershell -noprofile -file .\esomover.ps1
Upvotes: 0