0

I am trying to loop through a folder of files and rename them based on the last characters of the file. These files do not have extensions. My goal is:

  1. file ends with TXT eg ItemTXT, move it to the same location and rename as Item.txt
  2. file does not end with TXT, move it to the same location and rename as Item.xxx

I think I on the right track, but for some reason the if/else returns the else consition every time I test

@echo off
setlocal EnableDelayedExpansion
set pat=C:\Users\king\latest30

    echo %pat%
    for %%g in (%pat%\*) do (
        set fnamelast3="%%~nxg:~-3%"
        echo filename: %%~nxg fnamelast3: %fnamelast3%
        if "%fnamelast3%" neq "TXT" (
        echo %pat%/%%~nxg.fil 
        ) ELSE (
        rem does send with TXT
        echo %pat%/%fname%.txt 
        )
    )
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected) - even though you are setting `delayedexpansion`, you are not **using** it. Use `set "var=value"` for setting string values - this avoids problems caused by trailing spaces. Don't assign `"` or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier. You should find that `%%g in (%pat%\*.)` will select extensionless files. – Magoo Feb 02 '23 at 16:53
  • `set fnamelast3="%%~nxg:~-3%"` is invalid; you can't substring `metavariables` like `%%g`. You need to use `set "fname=%%~nxg"&set "fnamelast3=!fname:~-3!"&set "fnameexcept3=!fname:~0,-3!"` then use `!fnamelast3!` & `!fnameexcept3!` o\to rename your file - and you no longer need to detect `txt` since you will only be processing extensionless files which get their last three characters used as an extension – Magoo Feb 02 '23 at 17:00
  • @Magoo your suggestion worked perfectly thank you. If you want to type this up as an answer I would be happy to accept it – Rilcon42 Feb 02 '23 at 17:28

1 Answers1

0

Variables are not behaving as expected

  • even though you are setting delayedexpansion, you are not using it.

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign " or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier.

You should find that %%g in (%pat%\*.) will select extensionless files.

set fnamelast3="%%~nxg:~-3%" 

is invalid; you can't substring metavariables like %%g. You need to use

set "fname=%%~nxg"&set "fnamelast3=!fname:~-3!"&set "fnameexcept3=!fname:~0,-3!" 

then use !fnamelast3! & !fnameexcept3! to rename your file - and you no longer need to detect txt since you will only be processing extensionless files which get their last three characters used as an extension

Magoo
  • 77,302
  • 8
  • 62
  • 84