Wednesday, November 7, 2012

Reading Text from a text file into an Environment Variable.

Simply two methods Smile:

  1. Set /P MyText=<C:\MyTextFile.txt
  2. For /F %f in (tmp.txt) do Set MyText=%f.(Note: In batch files, use %%f).

Method 1 is quite simple. It will simply read text from MyTextFile.txt and would redirect the Input to MyText environment variable using ‘<’ operator.

Basically ‘Set /P’ is used to get user input while prompting the user. But using redirection operation ‘<’, we can read files into the prompting variable.

For more information about Set command, please see this link Or at command prompt type ‘Set /?’ and you’ll get a quick help.

 

Method 2 is little bit complex due to its longer syntax, but actually it is more versatile as you can do many other things with the Text you read.

For details about For command, at command prompt type For /? or see this link.

Using above mentioned ‘For’ command, your text would be read into %f and after ‘do’ attribute you can issue any command. E.g:

For /F %f in (tmp.txt) do echo %f

For /F %f in (tmp.txt) do echo %f >> C:\MyNewTextFile.txt (This would append value of %f into C:\MyNewTextFile.txt)

No comments: