0

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?

  • See http://stackoverflow.com/questions/1295068/windows-equiv-of-the-head-command for some ideas. In 'nix one would use the `head` command... The link discusses cmd alternatives – Floris Jan 14 '14 at 05:20
  • Re-read the question. I hope to get the first line to **a variable**. – user3186610 Jan 14 '14 at 05:28
  • I think that getting the first line is the first step to "getting it in a variable". Did you see http://stackoverflow.com/a/7827243/1967396 ? – Floris Jan 14 '14 at 05:36

2 Answers2

2

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

  • If the file to be read does not exist the previous content of the variable is not changed
  • If the first line in file is empty, the previous content of the variable is not changed
  • If the first line only contains spaces, this will be the content of the variable
  • Tab characters at the end of the line are ignored, so, a line with only tabs is considered empty and the variable value not changed

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"
MC ND
  • 69,615
  • 8
  • 84
  • 126
0
for /f "delims=" %%a in (%~dp0\directuse.txt) do set directusepermission=%%a&goto done
:done

should suffice.

Magoo
  • 77,302
  • 8
  • 62
  • 84