Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard to get files by exact extension

While diagnosing a larger batch script that needs to loop files with *.log extension I've found a funny behaviour. In a sample directory with files like this:

bar.log
foo.log
foo.log.ignore
foo.log.log-1676521099
not-related

... my little test script:

@echo off
setlocal enabledelayedexpansion
set DEF_LOG="C:\test\*.log"
for %%i in (%DEF_LOG%) do (
    echo %%i
)

... prints this:

C:\test\bar.log
C:\test\foo.log
C:\test\foo.log.log-1676521099

Digging deeper, I've found that's how Windows wildcards have been designed:

C:\>dir "C:\test\*.log" /b
bar.log
foo.log
foo.log.log-1676521099

My question is: how can I list all files that end exactly with .log?

like image 323
Álvaro González Avatar asked Dec 24 '13 12:12

Álvaro González


2 Answers

The Easyiest and faster way to do that is to test the modifier %%~x with your extension.

@echo off&cls
for /f "delims=" %%a in ('dir /b') do if /i "%%~xa"==".log" echo %%a
pause
like image 157
SachaDee Avatar answered Oct 06 '22 10:10

SachaDee


The source of the behavior is short file names. Unless disabled, file names that exceed the old 8.3 format will be assigned a short name that does match the 8.3 format. If the extension exceeds 3 characters, then the short name will consist of the first 3 characters of the long name extension. Execute the dir /x "C:\test\*.log" to see the short names.

All commands will test both the long and the short name when looking for matches.

A common way to get your desired result is to use DIR /B piped to FINDSTR. Note that you should avoid using delayed expansion when expanding a FOR variable because that will corrupt values that contain !. The ! character may appear in a file name.

@echo off
pushd "C:\test"
for /f "eol=: delims=" %%F in ('dir *.log^|findstr /lie ".log"') do echo %%~fF
popd
like image 41
dbenham Avatar answered Oct 06 '22 09:10

dbenham