0

I have a file named 01_tiago_miguel.txt and this code:

setlocal EnableExtensions DisableDelayedExpansion
for %%A in ("*_*") do (
    rem // Store current item:
    set "FILE=%%~A"
    rem // Toggle delayed expansion to avoid loss of or trouble with `!`:
    setlocal EnableDelayedExpansion
    rem // Remove everything up to and including the first `_`:

    echo ren "!FILE!" "!FILE:*_=!"
)
endlocal
exit /B

This gives the output:

ren "01_tiago_miguel.txt" "tiago_miguel.txt"

Which is exactly what I want - remove the first three characters.

However if I remove the echo it renames to miguel.txt, which doesn't make much sense since the output of the echo seems correct. Any idea why?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Tiago
  • 1,116
  • 5
  • 25
  • 39
  • Possible duplicate of [At which point does \`for\` or \`for /R\` enumerate the directory (tree)?](http://stackoverflow.com/questions/31975093/at-which-point-does-for-or-for-r-enumerate-the-directory-tree) – aschipfl Jan 04 '17 at 12:23
  • Just a side note: changing the mask from `*_*` to `??_*` would help to avoid renaming files again when running the script a second time... – aschipfl Jan 04 '17 at 12:25
  • _…and this is why I specifically mentioned the pattern and used it in my answer to your last question_. My alternative solution would be that you move and rename to a different or holding directory so that the files cannot be reprocessed. – Compo Jan 04 '17 at 12:45

1 Answers1

1

Use

for /f "delims=" %%A in (`dir /b /a-d "*_*"') do (

What is happening is that your echo doesn't rename the file (duh) but removing it does.

ren "01_tiago_miguel.txt" "tiago_miguel.txt" is executed, so the new filename is tiago_miguel.txt,

BUT

tiago_miguel.txt also fits the *_* mask, so

ren "tiago_miguel.txt" "miguel.txt" is executed, so the new filename is miguel.txt.

Using the dir command does a directory list and then processes the list, so any changes made are not re-encountered.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Magoo
  • 77,302
  • 8
  • 62
  • 84