2
@echo 

cd\

cd C:\Test\pdf

for /f "delims=" %%i in ('dir /b | findstr /E /R "\\BW RRI - [0-9]\.[0-9]\PAYMENT CONFIRMATION.pdf$"') do set "Filename=%%i" ren ("%FileName%" "test.pdf")

EXIT

So i am trying to run above batch to find a file and rename it. Filename has space. When i run just the following command in command prompt it finds the right file

 dir /b | findstr /E /R "\\BW RRI - [0-9]\.[0-9]\PAYMENT CONFIRMATION.pdf$"

But when i use for loop to rename it, it does not work. what am i doing wrong ?

PPrat
  • 39
  • 4
  • Why you use in the for-loop the %%i and the %%a. I think this could be your error. – Sascha Jan 15 '17 at 22:09
  • That was the typo as i was trying to change the name when pasting in stack overflow. Even when i use %%i only it still does not work – PPrat Jan 15 '17 at 22:11
  • 2
    Do you actually have the `set` and `ren` commands on the same line? You can't do that. – SomethingDark Jan 15 '17 at 22:19
  • 2
    The pipe symbol inside the for has to be escaped `^|` –  Jan 15 '17 at 22:55
  • ^| did the trick thank you!! – PPrat Jan 16 '17 at 00:55
  • I'd add the `/I` switch to `findstr` to treat the file names case-insensitively like Windows does... – aschipfl Jan 16 '17 at 07:38
  • 1
    If you expect that your suggested and so far uncorrected `findstr` will match a filename from the `dir /b` command output, then I very much doubt that it will. As you are aware a backslash will escape the next character, this means that you are expecting a filename containing an illegal character and an integer followed by `AYMENT`… In addition I see no benefit in not using `Dir/B/A-D "*PAYMENT CONFIRMATION.pdf^| FindStr`… – Compo Jan 16 '17 at 11:01
  • @Compo, the single `\ `in front of `P` is simply ignored (as there is nothing to escape)... – aschipfl Jan 16 '17 at 18:16
  • 1
    I understand that, what I was trying to get at was that because `AYMENT` wasn't intended, there shouldn't have been an escape character there in the first place. Also because of the additional incorrect expectation of the file name beginning with a backslash, the entire command is wrong. I would suggest that the OP is really looking for a file named "PAYMENT CONFIRMATION.pdf" they should be doing a recursive search and matching ones which are found in a directory whose name matches "BW RRI - _i.i_" where _i_ is a single digit integer. – Compo Jan 16 '17 at 18:40

1 Answers1

0

3 errors.

First, the entire for /f... line will be parsed and any %var% replaced by its then-current value, so the ren clause will become ren ("" "test.pdf")

Second, the parentheses would be included in the parameters to ren and should be removed

Third, the set clause and the ren should be separated by & to cascade the instructions.

.... do ren "%%i" "test.pdf"

should fix the problem. There is no need to set filename.

Magoo
  • 77,302
  • 8
  • 62
  • 84