Batch Read Line From File Into Variable

Declaration

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the ‘for’ loop needs to be used to serve this purpose. Let’s look at an example on how this can be achieved. If you are trying to read one line at a time then yes batch is quite capable of doing this. If you are trying to read in an entire file into a variable then no, batch can't do this but it can be done by reading in the file one line at a time into an array. Batch file set each line in a file as a variable I have the following code: for /F 'delims='%%i in (test.txt) do set content=%content%%%i This sets the last line of 'test.txt' as the%content% variable. Batch file set each line in a file as a variable I have the following code: for /F 'delims='%%i in (test.txt) do set content=%content%%%i This sets the last line of 'test.txt' as the%content% variable. FOR /F 'delims= '%%f in (yourfile.txt) DO echo%%f. Here’s my simple batch file that reads a text file, line by line, and passes each line to another batch file to perform an action. The second variable, “%%g”, is there because DelOld expects 2 parameters and FOR interprets a space in a line as a delimiter.

To create a simple variable and assign it to a value or string use the SET command:

Here, the code declares a new variable var with a value of 10. By default all variables are stored internally as strings; this means that the value 10 is no different to foo1234 or Hello, World!

Notes about quotation marks

Quotation marks used will be included in the variable's value:

Spaces in variables

Batch language considers spaces to be acceptable parts of variable names. For instance, set var = 10 will result in a variable called var that contains the value 10 (note the extra space to the right of var and the left of the 10).

Using quotation marks to eliminate spaces

In order to prevent spaces, use quotation marks around the entire assignment; the variable name and value. This also prevents accidental trailing spaces at the end of the line (the character denotes a space):

Also, use quotation marks when joining multiple statements with & or | - alternatively, put the symbol directly after the end of the variable's value:

Usage

This code will echo the value of var

If setLocal EnableDelayedExpansion is used, the following will echo the value of var (the standard expression %var% will not work in that context).

In batch files, variables can be used in any context, including as parts of commands or parts of other variables. You may not call a variable prior to defining it.

Using variables as commands:

Using variables in other variables:

Variable Substitution

Unlike other programming languages, in a batch file a variable is substituted by its actual value before the batch script is run. In other words, the substitution is made when the script is read into memory by the command processor, not when the script is later run.

This enables the use of variables as commands within the script, and as part of other variable names in the script, etc. The 'script' in this context being a line - or block - of code, surrounded by round brackets: ().

But this behaviour does mean that you cannot change a variable's value inside a block!

will print

Read

since (as you see, when watching the script run in the command window) it is evaluated to:

In the above example, the ECHO command is evaluated as Hello when the script is read into memory, so the script will echo Hello forever, however many passes are made through the script.

The way to achieve the more 'traditional' variable behaviour (of the variable being expanded whilst the script is running) is to enable 'delayed expansion'. This involves adding that command into the script prior to the loop instruction (usually a FOR loop, in a batch script), and using an exclamation mark (!) instead of a percent sign (%) in the variable's name:

will print

Batch Read Line From File Into Variable

The syntax %%a in (1,1,2) causes the loop to run 2 times: on the first occasion, the variable bears its initial value of 'Hello', but on the second pass through the loop - having executed the second SET instruction as the last action on the 1st pass - this has changed to the revised value 'Goodbye'.

Batch Read First Line From File Into Variable

Advanced variable substitution

Now, an advanced technique. Using the CALL command allows the batch command processor to expand a variable located on the same line of the script. This can deliver multilevel expansion, by repeated CALL and modifier use.

This is useful in, for example, a FOR loop. As in the following example, where we have a numbered list of variables:

'c:MyFilestest1.txt' 'c:MyFilestest2.txt' 'c:MyFilestest3.txt'

We can achieve this using the following FOR loop:

Output:

Note that the variable !i! is first expanded to its initial value, 1, then the resulting variable, %1, is expanded to its actual value of c:MyFilestest1.txt. This is double expansion of the variable i. On the next line, i is again double expanded, by use of the CALL ECHO command together with the %% variable prefix, then printed to the screen (i.e. displayed on screen).

On each successive pass through the loop, the initial number is increased by 1 (due to the code i+=1). Thus it increases to 2 on the 2nd pass through the loop, and to 3 on the 3rd pass. Thus the string echoed to the screen alters with each pass.

Declare multiple variables

When multiple variables are defined at the beginning of the batch, a short definition form may be used by employing a replacement string.

Note in the above example, variables are natively alphabetically sorted, when printed to screen.

Using a Variable as an Array

It is possible to create a set of variables that can act similar to an array (although they are not an actual array object) by using spaces in the SET statement:

Result:

It is also possible to declare your variable using indexes so you may retrieve specific information. This will create multiple variables, with the illusion of an array:

Result:

Note that in the example above, you cannot reference var without stating what the desired index is, because var does not exist in its own. This example also uses setlocal enabledelayedexpansion in conjunction with the exclamation points at !var[%%a]!. You can view more information about this in the Variable Substitution Scope Documentation.

Operations on Variables

Batch Read Line From File Into Variable

The final value of var is 20.

The second line is not working within a command block used for example on an IF condition or on a FOR loop as delayed expansion would be needed instead of standard environment variable expansion.

Here is another, better way working also in a command block:

The command prompt environment supports with signed 32-bit integer values:

  • addition + and +=
  • subtraction - and -=
  • multiplication * and *=
  • division / and /=
  • modulus division % and %=
  • bitwise AND &
  • bitwise OR |
  • bitwise NOT ~
  • bitwise XOR ^
  • bitwise left shift <<
  • bitwise right shift >>
  • logical NOT !
  • unary minus -
  • grouping with ( and )

The Windows command interpreter does not support 64-bit integer values or floating point values in arithmetic expressions.

Note: The operator % must be written in a batch file as %% to be interpreted as operator.

In a command prompt window executing the command line set /A Value=8 % 3 assigns the value 2 to environment variable Value and additionally outputs 2.

In a batch file must be written set /A Value=8 %% 3 to assign the value 2 to environment variable Value and nothing is output respectively written to handle STDOUT (standard output). A line set /A Value=8 % 3 in a batch file would result in error message Missing operator on execution of the batch file.

The environment requires the switch /A for arithmetic operations only, not for ordinary string variables.

Every string in the arithmetic expression after set /A being whether a number nor an operator is automatically interpreted as name of an environment variable.

For that reason referencing the value of a variable with %variable% or with !variable! is not necessary when the variable name consists only of word characters (0-9A-Za-z_) with first character not being a digit which is especially helpful within a command block starting with ( and ending with a matching ).

Numbers are converted from string to integer with C/C++ function strtol with base being zero which means automatic base determination which can easily result in unexpected results.

Batch

Example:

The output of this example is:

Batch Read Line From File Into Variable Speed

Batch read line from file into variable form

Variables not defined on evaluation of the arithmetic expression are substituted with value 0.

Setting variables from an input

Using the /p switch with the SET command you can define variables from an Input.

This input can be a user Input (keyboard) :

Which can be simplified like this :

Or you can get the input from a file :

in this case you'll get the value of the first line from file.txt

Getting the value of various line in a file :


Hello everyone, a friend of mine requested that I create a batch script for him that will transform a text file, full of names, into a series of folders with those same names. I know how to do this but I need help with the very first part. Reading from the text file.
Batch Read Line From File Into VariableThis is what I have so far for this fuction:
Then I would use the variables to create the dirs I need. But for some reason I get an error:
(EDIT) I fixed the error because I was using cmd to run the code. Changed %% to % and that got rid of the first problem. Sorry about that, but now there is this one.

Code: Select all


For the record I have no experence with using the 'for' command or any of its functions. Mostly because I havent really been able to find someone to help me with it. It is kind of confusing to me. Anyways I also need the delimiter for a carrage return if anyone knows it. I could also do this in vbs but I would like to try this first.
Thx in advance
-Phill