Search code examples
variablesfor-loopexpandbatch-file

Batch Script Removing characters from a variable inside a FOR loop


SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%A IN (*.*) DO (
 SET var=%%A
 ECHO !var:~0,-4!
)

Since we're iterating the variable within the FOR loop, you have to use ! around the variable, however, in conjunction with the method :~#,-# to remove characters from the end of the variable, it doesn't take.

In my example, we are just removing the extension from the filename. I understand that you can use %%~nA to just get the filename, but this is just an example of usage.

Is there a way to do this inside of the FOR loop? Maybe a different method than what I am using?


Solution

  • It could fail if there are hidden spaces behind set var=%%A.
    Then you only remove the spaces, therefore it's better to use

    set "var=%%A"

    It's independent of hidden spaces, even characers are ignored behind the last quote.

    But perhaps your problem is of a completly different type?