1.

Solve : Batch file to check file size then rename?

Answer»

I am currently trying to create a batch file to rename a log file to if it exceed 200kb. can anyone help me out.

i can rename the file with this command.

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "send.log" send%%e-%%f-%%g.log

 
but can anyone tell me what command to use for batch file to check it the log file exceed 200kb.

 
thanks in advance.

Welcome to the CH forums.

Start by checking the filesize:

ECHO off
cls

for /f "skip=4 tokens=4" %%a in ('dir send.log') do (
    set size=%%a & goto end
)

:end
set size=%size:,=%

if %size% gtr 200000 ren etc.....

Good luck1. If you use dir /b instead of plain dir you can avoid the tokens & skips. In any case you can get at the file properties directly without any DIR stuff at all or the /f switch by simply enclosing the filename in quotes.

2. File sizes are generally measured in powers of 2, and disk capacities using powers of 10, thus 200 kB file size ought really to be 204800 bytes. I don't suppose it matters, but I am a bit old skool about these things. Could lose marks if this is a school project!

An easy way to work it out



So,

3.

Code: [Select]for %%S in ("send.log") do set /a fsize=%%~zS
if %fsize% GTR 204800 (
   for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "send.log" send%%e-%%f-%%g.log
)

4. Alternatively, using variables to avoid hardwiring VALUES into the operational code (ANOTHER old skool thing!)

Using "magic numbers" is severely deprecated in programming courses (or should be)

Code: [Select]set maxlogsize=204800
set oldname=send.log
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do set newname=send%%e-%%f-%%g.log
for %%S in ("%oldname%") do if %%~zS GTR %maxlogsize% ren "%oldname%" "%newname%"

Either codes (3) or (4) should do the job as defined. However:

5. That method of slicing up the %date% variable will give different results if your locale settings do not use US date format. On my system, where currently, %date% expands to the non-US format, 08/08/2008 (day/month/year), send.log got renamed to send08-2008-.log

How to get a standardized date string (I would be interested if someone could check this works on US style dates)

I found this on alt.msdos.batch.nt - that set %%a= stuff looks kinda odd (=intriguing) but it seems to work...

Code: [Select]if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
  for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
    set %%a=%%i
    set %%b=%%j
    set %%C=%%k
    )
)
if %yy% LSS 100 set yy=20%yy%
set Today=%yy%-%mm%-%dd%
echo %today%
Among other things, it pipes a CR to the date command & looks at the second line of the output to see what format the user is prompted to enter, it sees this in the UK:

Code: [Select]Enter the new date: (dd-mm-yy)



Discussion

No Comment Found