Home > other >  Batch Script to execute command only for files above a certain size,
Batch Script to execute command only for files above a certain size,

Time:11-14

I am trying to run the Imagemagick mogrify only on files that are above a 1,500kb. The Imagemagick command would be magick mogrify *.jpg -resize 50%% *.jpg

So after researching on my own I have ended up with this

@echo off
setlocal
set maxbytesize=1500000

FOR /F %%A IN (*.jpg) DO set size=%%~zA

if %size% GTR %maxbytesize% (
    magick mogrify *.jpg -resize 50%% *.jpg
)

This doesn't work and I have no idea where to go from here. I have read on https://unix.stackexchange.com/questions/38943/use-mogrify-to-resize-large-files-while-ignoring-small-ones that I may have to filter through the list first though I don't know how to implement it. Any help is appreciated. Thanks for reading this post.

CodePudding user response:

Your value will be replaced through each iteration of the files (besides the fact that /F causing another issue here as well, see for /? for more detail)

So only the value of the last file is set as the value. Additionally, even if they were not, you are doing magick on *.jpg, which is all jpg files in the directory. So if the last file seems to match the size, all files will be resized, which will kind of defeating the purpose, right?

All you really need is to iterate through files, match the size each time, then perform the action:

@echo off
for %%A IN (*.jpg) DO if %%~zA gtr 1500000 magick mogrify "%%~A" -resize 50%% "%%~A"

CodePudding user response:

Just for the sake of being different, here's an example which pre-filters the target files prior to the do portion of the for loop, instead of passing it everything, and then filtering their sizes.

Additionally, I have modified the mogrify parameters, because if I remember correctly, the resizing automatically overwrites the source file.

Please remember to input your actual Source and Magick Paths on lines 4 and 5, before you run the script.

@Echo Off
SetLocal EnableExtensons

Set "SourcePath=S:\ource\Directory"
Set "MagickPath=%ProgramFiles%\ImageMagick-7.1.0-Q16-HDRI"

If Not Exist "%MagickPath%\magick.exe" GoTo :EOF
CD /D "%SourcePath%" 2>NUL || GoTo :EOF

Set "}=           
  • Related