0

I have a batch file that essentially finds all the pdf files in a folder, and gives them a prefix. SO example: file1.pdf & file2.pdf. When the batch file runs, it adds a prefix, let's say "new" to each file. New - file1.pdf & New - file2.pdf.

I'm unsure of how to get this to check to see if this file already contains this prefix and skip it if true. Here's my current code:

set strPrefix=New - 

set fname=*.pdf

for %%f in (%fname%) Do echo Rename file "%%f" to "%strPrefix%%%f"

for %%f in (%fname%) Do ren "%%f" "%strPrefix%%%f"
ankh-morpork
  • 1,732
  • 1
  • 19
  • 28
Tweak000
  • 15
  • 1
  • 4
  • Have you tried a [substring](http://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file)? – Bacon Bits Aug 10 '15 at 14:28

2 Answers2

2

Use DIR /B to list the files and pipe the result to FINDSTR to remove the files that aready have the prefix. Process that result with FOR /F (instead of a simple FOR).

@echo off
setlocal
set "prefix=New - "
set "mask=*.pdf"

for /f "eol=: delims=" %%F in (
  'dir /b "%mask%" ^| findstr /vibc:"%prefix%"'
) do ren "%%F" "%prefix%%%F"

Or you could use my JREN.BAT regular expression file renaming utility to do things more simply. It is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward. Full documentation is embedded within the script.

The following command (for the command line) assumes JREN.BAT is in a folder that is listed within your PATH.

jren "^" "New - " /fm "*.pdf" /fx "New - *"

Use CALL JREN if you put the command within a batch script.

dbenham
  • 127,446
  • 28
  • 251
  • 390
0

The following code extracts the beginning of the filename and compares it with your predefined prefix (in a case-insensitive manner):

set "strPrefix=New - "
set lenPrefix=6
set fname=*.pdf

setlocal EnableDelayedExpansion
for %%F in (%fname%) do (
  set "file=%%~nxF"
  if /i not "!file:~0,6!"=="%strPrefix%" (
    ren "%%~fF" "%strPrefix%%%~nxF"
  )
)
endlocal

The variable lenPrefix holds the length (number of characters) of the prefix, bacause there is no built-in function to get it.

foxidrive
  • 40,353
  • 10
  • 53
  • 68
aschipfl
  • 33,626
  • 12
  • 54
  • 99