0

My batch file execution throws error at echo echo %outfvar%. The following is the batch file I wrote:

setlocal ENABLEDELAYEDEXPANSION
set /a incvar = 1
set outfvar = "outfile"_!incvar!".res"
echo !outfvar!
echo *.txt > !outfvar!
set /a incvar = incvar+1

FOR %%pat in (%*) do(
    FOR /F %%k in (!outfvar!) DO( grep -l !pat! !k! >>outfile_!incvar!.res)
    set /a incvar = incvar+1
    set outfvar = "outfile"_!incvar!.res
                     )

Error is "%pat was unexpected at this time.." Can anybody help me to execute this batch file successfully?

Smij01
  • 45
  • 9
  • it's actually not a good idea to edit the question so that the solutions from the answer(s) are implemented; imagine other users viewing the post...; a better way is to provide an answer wher you present your solution... – aschipfl Sep 03 '15 at 11:45
  • I've rolled back the changes to the question - @Smij01 the aim is to accept an answer that solves your question - using the green tick when it becomes available, (see the help tour). You can ask another question to solve a different problem. – foxidrive Sep 03 '15 at 17:58

1 Answers1

3

Remove the spaces around = in all set commands.

There must be a space in between do and ( in the line of for.

The line

set outfvar = "outfile"_%incvar%".res"

should read

set "outfvar=outfile_%incvar%.res"

(The quotes as you stated them were part of the string value.)

for variables must consist of one letter only and need to be expanded by preceding with %%. You are trying to use %%pat in your code, which will not work. State %%p instead (also inner for).

Finally, you need delayed expansion to be able to read variables you modify within the same (compound) command, the for in your code. See this post to learn how it works.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • also needs delayed expansion – npocmaka Sep 03 '15 at 11:13
  • @aschipfl: I have removed the spaces around = and added space between do and ( as you have instructed. now I am getting another error : %pat was unexpected at this time. – Smij01 Sep 03 '15 at 11:28
  • @aschipfl: I have changed using delayed expansion. But still I am getting "%pat was unexpected at this time." – Smij01 Sep 04 '15 at 02:16
  • You are trying to use `%%pat` as a variable of `for` -- as I mentioned in my answer... by the way, you should insert a space in between `do` and `(` at both `for` lines... – aschipfl Sep 04 '15 at 02:24
  • So how should I correct it? I am new to batch programs, so don't mind if my doubt seems so silly. – Smij01 Sep 04 '15 at 04:31