tresstylez tresstylez - 1 year ago 61
Bash Question

For loop in batch file reading a file of File Paths

I want to write a Windows batch file script that will loop through a text file of FILE PATHS, do some work using data from each file path, then ultimately delete the file.

I started by running the FORFILES command and sending its output (the @PATH parameter is the full path of any file it matches) to a text file (results.txt).

I end up with a results.txt file like this:


What I want to do is:

  • Use a FOR loop and read each line in the results.txt file

  • For each line (file path), strip out the directory name that the log file is sitting in (ie: Dir1, Dir2, etc..) and create a directory with that SAME name in a different location (ie. D:/Archive/Backups/Dir1, D:/Archive/Backups/Dir2, etc..) -- assuming the directory doesn't exist.

  • Move the actual .log file to a zip file in that directory [I have code to do this].

  • Delete the .log file from its original location. [Pretty straightforward]

I'm having trouble figuring out the best way to accomplish the first 2 steps. My FOR loop seems to stop after reading the very first line:

FOR /F "tokens=1,2,3,4,5,6,7,8,9,10 delims=\" %%G in ("results.txt") DO (

Answer Source

You don't want to parse the path with the tokens/delims options because you don't know how many directory levels you are dealing with. You want to preserve each line in its entirety. TO parse the path you want to use the FOR variable modifiers. (type HELP FOR from the command line and look at the last section of the output)

%%~pG gives the path (without the drive or file name). If we then strip off the last \, we can go through another FOR iteration and get the name (and possible extension) of the file's directory by using %%~nxA.

The toggling of delayed expansion is just to protect against a possible ! in the path. If you know that no path contains ! then you can simply enable delayed expansion at the top of the script and be done with it.

EDIT - this code has been modified significantly since Aacini pointed out that I misread the requirements. It should satisfy the requirements now.

for /f "usebackq delims=" %%G in ("results.txt") do (
  set "myPath=%~pG"
  setlocal enableDelayedExpansion
  for /f "eol=: delims=" %%A in ("!myPath:~0,-1!") do (
    if not exist d:\Archive\Backups\%%~nxA md d:\Archive\Backups\%%~nxA
    rem ::zip %%G into zip file in the D: location
    rem ::you should be able to create the zip with the move option
    rem ::so you don't have to del the file