I want to set a variable "directusepermission" as the first line of a txt file.
set /p directusepermission=<%~dp0\directuse.txt-first-line
So I want the first line only. How can I do so?
I want to set a variable "directusepermission" as the first line of a txt file.
set /p directusepermission=<%~dp0\directuse.txt-first-line
So I want the first line only. How can I do so?
What you have should be enough.
set /p "var="<file
or
<file set /p "var="
will read the first line in file
into variable var
.
In your code, the problem can be the path to the current batch file. If it contains spaces, the file name must be quoted.
set /p "directusepermission=" < "%~dp0\directuse.txt"
Also, when reading variables this way you will need to check for
You can also use the for /f
command to iterate over the file contents. In this case the non existing file "problem" still exists, but blank lines are ignored, either if they are empty or contains only spaces or tabs.
But to only get the first line, you will need some code to determine that only first line will be asigned to variable.
This iterates over all the file contents, but only assigns the first line to the variable. For single line or small files, this is the simplest. tokens=*
ask for
command to retrieve all the line and useback
parameter has been included to avoid that quoted file names are considered strings to process.
set "var="
for /f "tokens=* usebackq" %%f in ("file") do if not defined var set "var=%%f"
This retrieves only the first line of file, but requires an aditional label where to jump to get out of the for command
for /f "tokens=* usebackq" %%f in ("file") do set "var=%%f" & goto endLoop
:endLoop
If you know what content is in the line you want to retrieve, file can be filtered to get only the desired line(s). This returns only lines with numbers from start to end of the line, and the last line (remember it is iterating over the returned lines) will be asigned to the variable
for /f "tokens=*" %%f in ('findstr /r "^[0-9][0-9]*$" <"file"') do set "var=%%f"
for /f "delims=" %%a in (%~dp0\directuse.txt) do set directusepermission=%%a&goto done
:done
should suffice.