1.

Solve : Extract first letter from file names, and move files in to folder...?

Answer»

Hello all.

First of all, I wish you all a great 2012!

Second, my question / problem:

I have ~1500 text files CONTAINING lyrics, and they're ORGANISED in folders following the artist name. E.g.: \Rush\Rush - Tom Sawyer.txt


I want to re-organise the files, so that they match the same scheme used by Evil Lyrics, which is by artist's first letter: \R\Rush - Tom Sawyer.txt.

So, what I need to do is:

  • Extract the first letter of the file name
  • Move the file to a path which consists of a base-path + first letter

To extract the first letter of a variable is pretty simple:

Code: [Select]set str=1234
set str=%str:~0,1%
echo %str%

In the example above, first str is set to "1234", and then set to the first character, resulting in "1".

So I thought I could use the above technique and the FOR command. However, I just can't extract the first letter from file names within the FOR command.

For instance, in the code below I attempt to, for each TXT file in the folder:

  • reduce the file to just the file name (by using %%~n to remove the path)
  • set variable STR with the file name
  • echo the reduced file name
  • echo the variable

Code: [Select]cls
echo off
set /p str=""

for %%f in (*.txt) DO (

set str=%%~nf
echo this is the filename: %%~nf
echo this is the variable: %str%
pause

)

exit


But what actually happens is that the result of line (3) is OK, changing for each file, while variable STR echoed in line (4) remains fixed with a value that was set at some point.

My conclusion is that variable STR never is set with the file name. Or maybe it is, but only once.

I looked in to expanding the variable by using "!" (e.g.: !str!), but I couldn't get that to work.


Once I do get to assign the file name to a variable, then I can extract the first letter (as DESCRIBED, with %str:~0,1%) and proceed with my plan.

Any ideas on how I can achieve my objectives, and why I can't set the variable with a file name?

Thanks a lot,

Michael

You need to enable delayed expansion. This allows you to use the exclamations around your variable names.
echo off & setlocal enabledelayedexpansion Quote from: Squashman on December 31, 2011, 11:46:16 PM
You need to enable delayed expansion. This allows you to use the exclamations around your variable names.
echo off & setlocal enabledelayedexpansion

A-ha.... SOMETHING NEW I learned. I wasn't aware that it had to be explicitly enabled.

I'm not home right now but will work on this ASAP.

Thanks again,

Michael


Discussion

No Comment Found