-1

I want to iterate all files of my folder based on their file extension, and file names using a batch script.

I have the below code to get the file extension, and can echo it with %%~xa, but when I try to define it as file_extension, the output just returns as ECHO is off.

Can someone please tell me how to do it?

@echo off
setlocal EnableDelayedExpansion
 
for  %%a in (folder\*) do (
       
    echo Processing file = %%~nxa
    echo Processing file extension %%~xa
    echo Processing file name = %%~na
    SET file_extension = %%~xa
    echo !file_extension!
    echo %%~xa
)  
pause
Compo
  • 36,585
  • 5
  • 27
  • 39
  • 3
    SET is working, the issue is that you aren't using it correctly! If you change it to `echo !file_extension !`, it will work. However I would advise instead that you do it properly in the first place and use `SET file_extension=%%~xa`, or even better the recommended syntax, `Set "file_extension=%%~xa"`. – Compo May 07 '21 at 10:07

1 Answers1

0

cmd is not the same as the likes of perl, C# etc.

cmd actually uses the whitespace before and after = as part of the variable name and value. Currently your code SET file_extension = %%~xa will create a variable with trailing whitespace !File_extension ! and a leading space in the value. .txt.

so you must set it with not whitespace before or after =. It is better to also use double quotes around the variable and value inclusive, to also ensure that there are not any accidental whitespace after the value. for instance set var=val will create a variable of %var% correctly but an incorrect value of val .

So after all that is explained, here is a fixed version of your current code:

@echo off
setlocal EnableDelayedExpansion
 
for  %%a in ("folder\*") do (
       
    echo Processing file = %%~nxa
    echo Processing file extension %%~xa
    echo Processing file name = %%~na
    set "file_extension=%%~xa"
    echo !file_extension!
    echo %%~xa
)  
pause
Gerhard
  • 22,678
  • 7
  • 27
  • 43