Reputation: 23
I've got a problem with redirecting input from a file into set/p
Here is my script:
@echo off
echo Reading: {%1}
type %1
echo(
echo Starting...
set VAR=
set /P VAR=<%1
echo VAR is {%VAR%}...
I've read elsewhere (https://stackoverflow.com/a/7827243) that the syntax I am using will work. It does not!
Here is my output:
Reading: {Fruit.txt}
Pears
Apples
Oranges
Kiwi
Grapes
Kumquat
Starting...
VAR is { ■P}...
So - What gives?
Upvotes: 2
Views: 2613
Reputation: 130919
Your file is in Unicode (UTF16) format, and SET /P does not work with Unicode. The TYPE command does work with Unicode, and it converts the output to ANSI. You can redirect the output of TYPE to a new text file, and then your SET /P will work.
@echo off
type %1>new.txt
set VAR=
set /P VAR=<new.txt
echo VAR is {%VAR%}...
EDIT
To get the second line instead of the first:
@echo off
type %1>new.txt
<new.txt (
set /P VAR=
set VAR=
set /P VAR=
)
echo VAR is {%VAR%}...
Upvotes: 5
Reputation: 24585
Here's another technique for reading only the first line of a file using for /f and type that doesn't rely on set /p:
@echo off
setlocal enableextensions enabledelayedexpansion
set VAR=
set CURRLINE=0
for /f "delims=" %%a in ('type "test.txt"') do (
set /a CURRLINE+=1
if !CURRLINE! EQU 1 (
set VAR=%%a
goto :DONE
)
)
:DONE
echo %VAR%
endlocal
The advantage here is there's no need to write out a separate file.
However, note that either of these approaches (set /p or for /f with type) will have problems with special shell characters in the input file (<, >, |, etc.). To get around this problem, one could use a small utility I wrote a while back called shellesc.exe (http://www.westmesatech.com/sst.html) to "escape" the special characters. But if you use these tools, then you can also use linex.exe to pick the line you want and get the result with a little bit less code:
@echo off
setlocal enableextensions
set VAR=
for /f "delims=" %%a in ('type "test.txt" ^| linex -l 1 ^| shellesc') do set VAR=%%a
echo %VAR%
endlocal
Note that this approach has the additional advantage of not "choking" on special shell characters (shellesc).
HTH,
Bill
Upvotes: 0
Reputation: 24585
If the purpose is to read lines of text from a file, why do you need the set /p command?
for /f "delims=" %%a in ('type "file name.txt"') do echo %%a
If you type the command at the cmd.exe command line, you would write %a (one % symbol) rather than %%a (i.e., double the % symbol when using in a shell script [batch file]).
Bill
Upvotes: 1