Raj
Raj

Reputation: 887

Extracting Dir-Path and File-Name from absolute path of a file

Starting from a directory, I would like to:

  1. Recursively peek into each of the sub-folders
  2. Identify a list of files
  3. Apply changes on those files
  4. Return back to starting point and re-do 1 through 3 on the remaining directories

This is my attempt at doing it via DOS batch file:

 for /r . %%g in (*.pm) do (
  SET FILEPATH=??
  SET FILENAME=??
  SET CURRENT="%cd%"
  cd %FILEPATH%
  perl Perl_Script.pl %FILENAME%
  cd "%CURRENT"
   )

What should FILEPATH and FILENAME be set to?

Based on answer from Jakub, I modified the program to:

 for /r . %%g in (*.pm) do (
  SET FILEPATH="%%~pg"
  SET FILENAME="%%~g"
  SET CURRENT="%cd%"
  cd %FILEPATH%
  perl Perl_Script.pl %FILENAME%
  cd %CURRENT%
   )

I could acertain from the logs that FILENAME and FILEPATH were receiving the correct values, but for sime unfathomable reason, %FILEPATH% and %FILENAME% would ALWAYS be set to the value that was FIRST assigned to these variables.

After googling for several hours, I realized there was this delayedexpansion concept. In the end (and after a gruelling duel), it finally boiled down to this:

 setlocal enabledelayedexpansion
 for /r . %%g in (*.pm) do (
  SET FILEPATH="%%~pg"
  SET FILENAME="%%~g"
  SET CURRENT="%cd%"
  cd !FILEPATH!
  perl Perl_Script.pl !FILENAME!
  cd %CURRENT%
   )
 endlocal

Works like a charm!!!

Upvotes: 0

Views: 471

Answers (1)

Jakub Wasilewski
Jakub Wasilewski

Reputation: 2976

Here is an answer detailing how to split filenames into separate pieces of file information. In your case, you need %%~ng for the name, and %%~pg for the path.

Upvotes: 1

Related Questions