Question

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.

Was it helpful?

Solution

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!

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top