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?

2
  • 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
    Commented Sep 3, 2015 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
    Commented Sep 3, 2015 at 17:58

1 Answer 1

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.

5
  • also needs delayed expansion
    – npocmaka
    Commented Sep 3, 2015 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
    Commented Sep 3, 2015 at 11:28
  • @aschipfl: I have changed using delayed expansion. But still I am getting "%pat was unexpected at this time."
    – Smij01
    Commented Sep 4, 2015 at 2: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
    Commented Sep 4, 2015 at 2:24
  • So how should I correct it? I am new to batch programs, so don't mind if my doubt seems so silly.
    – Smij01
    Commented Sep 4, 2015 at 4:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.