batch find file extension

51,553

Solution 1

The FOR command has several built-in switches that allow you to modify file names. Try the following:

@echo off
for %%i in (*.*) do echo "%%~xi"

For further details, use help for to get a complete list of the modifiers - there are quite a few!

Solution 2

This works, although it's not blindingly fast:

@echo off
for %%f in (*.*) do call :procfile %%f
goto :eof

:procfile
    set fname=%1
    set ename=
:loop1
    if "%fname%"=="" (
        set ename=
        goto :exit1
    )
    if not "%fname:~-1%"=="." (
        set ename=%fname:~-1%%ename%
        set fname=%fname:~0,-1%
        goto :loop1
    )
:exit1
    echo.%ename%
    goto :eof

Solution 3

Sam's answer is definitely the easiest for what you want. But I wanted to add:

Don't set a variable inside the ()'s of a for and expect to use it right away, unless you have previously issued

setlocal ENABLEDELAYEDEXPANSION

and you are using ! instead of % to wrap the variable name. For instance,

@echo off
setlocal ENABLEDELAYEDEXPANSION

FOR %%f IN (*.*) DO (

   set t=%%f
   echo !t:~-3!

)

Check out

set /?

for more info.

The other alternative is to call a subroutine to do the set, like Pax shows.

Share:
51,553
Vhaerun
Author by

Vhaerun

Free time ? Perl/Ruby scripter : Java developer

Updated on July 09, 2022

Comments

  • Vhaerun
    Vhaerun almost 2 years

    If I am iterating over each file using :

    @echo off
    
    FOR %%f IN (*\*.\**) DO (
        echo %%f
    )
    

    how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : echo "%t:~-3%" to print but with no success.