Andrew Anderson
Andrew Anderson

Reputation: 1126

Listing all jpg files except ending with certain character in command line CMD

I want to echo all *.jpg files, except for *-.jpg, so for that I made this command:

for %i in (*.jpg) do if not "%i"=="*-.jpg" echo %~i

But it failed, because it echoed all jpg files.

To experiment I wrote this command:

for %i in (*.jpg) do if not "%i"=="*.jpg" echo %~i

I was expecting this command to echo no files, but it does echo jpg files despite the if not command.

What am I missing?

Update:

My goal is to rewrite my batch file with this content:

for %%i in (*.jpg) do magick "%%i" -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB "%%~ni"-.jpg

so that it makes the compression operation, only if the filename doesn't end with -.

I tried this with no success and successory investigations which led to this question:

for %%i in (*.jpg) do if not "%%ni"=="*-.jpg" magick "%%i" -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB "%%~ni"-.jpg

Upvotes: 0

Views: 519

Answers (2)

Andrew Anderson
Andrew Anderson

Reputation: 1126

This is the final batch file: FOR /F "usebackq delims=" %%i in (`DIR /B /A:-D "*.jpg" ^| find /V "-.jpg"`) DO magick "%%i" -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB "%%~ni"-.jpg

For reference: https://renenyffenegger.ch/notes/Windows/dirs/Windows/System32/cmd_exe/commands/for/f/command/index https://ss64.com/nt/for.html

Upvotes: 0

lit
lit

Reputation: 16256

Run the filenames through find.exe and omit those that contain -.jpg. The /V switch tells find.exe to omit lines where the string is found. Using findstr.exe uses a regex which can ensure that it is only found at the end of the filename. As always, use FIND /? and FINDSTR /? to read all about it.

DIR /B /A:-D "*.jpg" | "%SystemRoot%\system32\find.exe" /V "-.jpg"
    or
DIR /B /A:-D "*.jpg" | "%SystemRoot%\system32\findstr.exe" /V /R "\-\.jpg$"

If you want to step up to a modern day language, it is easy in PowerShell.

Get-ChildItem -File -Filter '*.jpg' | Where-Object { $_.Name -notmatch '\-\.jpg$' }

Updated question, updated answer

When the magick command line appears as you wish, remove the ECHO at the beginning of the line.

SET "EXT=jpg"
FOR /F "delims=" %%A IN ('DIR /B /A:-D "*.%EXT%" ^| "%SystemRoot%\system32\findstr.exe" /V /R "\-\.%EXT%$"') DO (
    ECHO magick "%%~A" -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB "%%~nA-.%EXT%"
)

In PowerShell

Get-ChildItem -File -Filter '*.jpg' |
    Where-Object { $_.Name -notmatch '\-\.jpg$' } |
    ForEach-Object {
        & magick "$_.FullName" -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB ("$_.BaseName" + "-.jpg")
    }

Upvotes: 1

Related Questions