0

I am reading a text file %tmp%\tmp.txt. I am trying to find a line with a given string (in this example "RemotePath") and it sets the variable netdrive to that line if it is found. Here is my code:

for /f "tokens=*" %%a in (%tmp%\tmp.txt) do echo.%%a|findstr /C:"RemotePath " >nul 2>&1 && set netdrive=%%a

It never sets netdrive to anything, however when i change the set netdrive=%%a to echo %%a >> netdrive.txt the text I want does come up in the text file. Any ideas?

Jordan
  • 124
  • 9

2 Answers2

0

It looks like you are repeatedly setting netdrive to each token from the input file, not the output of findstr. The final assignment probably gives it an empty value from the end of the file. To assign it from the output of findstr, see here: How do I get the result of a command in a variable in windows?

Community
  • 1
  • 1
underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • I tried this `for /f "tokens=*" %%a in (%tmp%\tmp.txt) do ( echo %%a | findstr /c:"RemotePath" if errorlevel 0 set netdrive=%%a )` but got the same result. Am I still setting netdrive to %%a to every line? – Jordan Jul 19 '15 at 18:57
  • %%a is always the latest token. I don't know about the return code of findstr so can't speculate on that. – underscore_d Jul 19 '15 at 19:27
0
for /f "tokens=*" %%a in ('findstr /C:"RemotePath " "%tmp%\tmp.txt"') do set "netdrive=%%a"

The "problem" with the original code is that each side of a pipe is executed in a separate process, so, in your case, the set command is running in another cmd instance and the variable is set in this separate instance, not in the instance that runs the batch file.

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Interesting. I tried this and I run into the error "The filename, directory name, or volume label syntax is incorrect." I checked and %tmp%\tmp.txt does exist. The file starts with an empty line. The second line contains a reg key path. The third line starts with a tab, and then says RemotePath blah blah blah (the line that I want to set to the variable netdrive. When I run the command within the parenthesis `findstr /C:"RemotePath " "%tmp%\tmp.txt"` it outputs the correct line to the console. What am I doing wrong? – Jordan Jul 21 '15 at 02:04
  • @Jordan, sorry, my fault. There was a typo error, a quote placed where it shouldn't be. Answer updated. – MC ND Jul 21 '15 at 04:42