1

I have been trying to achieve in an easy way to copy image files to a server through ftp. Exiting files are using P123456 structure and new files should receive a _number after them like P123456_1. I haven't managed to make them go sequentially but only in random mode with the below code.

set work=%temp%\%random%-%random%
mkdir "%work%"

set archives=*.rar

for %%A in (%archives%) do (
"%ProgramFiles(x86)%\7-Zip\7z.exe" e -o"%work%" "%%~A"
for %%F in ("%work%\*") do copy "%%~F" "%%~nF_%random%%%~xF"
)

rmdir "%work%"

The above code would be suffice if the new files would generate random numbers for each file in the archive but if i have P1, P2 and P3 in the the archive the batch would output P1_random-number, P2_same-random-number, P3_same-as-the-first-two "random" numbers instead of P1_random, P2-other-random etc.

2 Answers2

0

This is good example to describe the usage of Delayed expansion in batch files.

setlocal enabledelayedexpansion
set work=%temp%\!random!-!random!
mkdir "%work%"
set archives=*.rar

for %%A in (%archives%) do (
"%ProgramFiles(x86)%\7-Zip\7z.exe" e -o"%work%" "%%~A"
for %%F in ("%work%\*") do copy "%%~F" "%%~nF_!random!%%~xF"
 )
rmdir "%work%"
prudviraj
  • 3,634
  • 2
  • 16
  • 22
0

implementing a counter is easy:

setlocal enabledelayedexpansion
set work=%temp%\%random%-%random%
mkdir "%work%"
set archives=*.rar
set counter=0

for %%A in (%archives%) do (
  REM you should delete the contents of %work% for each new archive:
  rmdir /q /s "%work%"
  mkdir "%work%"
  "%ProgramFiles(x86)%\7-Zip\7z.exe" e -o"%work%" "%%~A"
  for %%F in ("%work%\*") do (
    call :getfreename "%%~F"
    copy "%%~F" "%%~nF_!counter!%%~xF"      )
)
rmdir /q /s "%work%"
goto :eof

:getfreename
set /a count+=1
if exist "%~n1_%counter%%~x1" goto :getfreename
goto :eof

for a short demonstration of delayed expansion, see here

Community
  • 1
  • 1
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Both answers work for first run but only prudviraj's version works for existing files, Stephans if i run the script twice (or by using prexistent files) the script doesn't do anything. Altough Stephan's script is closer to what i want i guess it needs an extra if file is existent add a +1? P.s. i don't know which answer to pick as the right since both are correct in another way :). – user2043628 Nov 17 '15 at 12:34
  • I added a check for existing files (see my edit) I had to do it outside of the `for` loop, because every `goto` would break the Loop. If you ran my first Version twice, the second run started again with `Counter=0`. The new Version should cover that (not tested!) – Stephan Nov 17 '15 at 14:13
  • if no existing answer fully satisfies you, you could add your own answer and accept that. – Stephan Nov 17 '15 at 14:16