2

Challenge

Expanding on this post, how can you prefix filenames to include their parent folder names. @dbenham response (see below) is great, but it only prefix' the immediate parent folder's name in filename. No Powershell allowed!

Before:

C:\Photos\cats
fileA.txt
fileB.txt
fileC.txt

After:

C:\Photos\cats
Photos_cats_fileA.txt
Photos_cats_fileB.txt
Photos_cats_fileC.txt

Where the divider "_" can be any character.

Near Solution

@dbenham's code from this post is as follows:

@echo off
pushd "Folder"
for /d %%D in (*) do (
  pushd "%%D"
  for /r %%F in (*) do (
    for %%P in ("%%F\..") do (
      ren "%%F" "%%~nxP_%%~nxF"
    )
  )
  popd
)
popd

What it does

C:\Photos\cats
cats_fileA.txt
cats_fileB.txt
cats_fileC.txt

Again, this doesn't include "Photos". How to include?

Pre-emptive thank you!

1 Answers1

0

In order to include the full filepath, you will need to do some variable processing, which doesn't work in batch for loops without enabling delayed expansion.

Use the batch file below in place of what you had originally.

@echo off
pushd "Folder"
setlocal enabledelayedexpansion
for /d %%D in (*) do (
  pushd "%%D"
  for /r %%F in (*) do (
    for %%P in ("%%F\..") do (
      set _path=%%~pnxP
      set _path=!_path:~1!
      ren "%%F" "!_path:\=_!_%%~nxF"
    )
  )
  popd
)
popd

The differences are:

  • setlocal enabledelayedexpansion - enable delayed expansion
  • set _path=%%~pnxP - create a variable to store the full path (excluding the drive letter) of the file
  • set _path=!_path:~1! - the full path includes the \ in C:\ at the beginning, so we need to strip that out.
  • echo "%%F" "!_path:\=_!_%%~nxF" - replace the backslashes with underscores
Worthwelle
  • 4,816