HalfOfAKebab
HalfOfAKebab

Reputation: 3

In Batch, using FIND or FINDSTR and saving its output to a variable with SET

I have a file that contains a lot of lines, e.g.

foo=1
foobar=2
bar=3

I want to use FIND (or FINDSTR) to read this file and use SET to set a variable foobar to 2, etc.

I would much prefer to only use Batch and tools that come with Windows - no third-party tools. But if it's impossible without any, then I'm open to using them.

Upvotes: 0

Views: 318

Answers (3)

mklement0
mklement0

Reputation: 438178

Since you've mentioned tools that come with Windows as an option:

PowerShell offers a simple and flexible solution (file is assumed as the name of the input file):

$settings = ConvertFrom-StringData (Get-Content -Raw file)

The command above (executed interactively or from a *.ps1 file) reads all =-separated key-value pairs into a single hash table, so you can easily access individual settings on demand; e.g.:

$settings.foobar  # -> 2 

Upvotes: 0

Magoo
Magoo

Reputation: 80033

What do you need find or findstr for?

If your file is structured as you suggest, then

for /f "delims=" %%a in (filename) do set "%%a"

will set those variables to the values.

Upvotes: 4

Paul Houle
Paul Houle

Reputation: 735

If the file holding your "var=value" lines is set.txt, the following will do it:

for /f "delims=^= tokens=1-2" %%v in (set.txt) do set %%v=%%w

I've made assumptions -- if there are more requirements/restrictions than how I've addressed the problem you must clarify the question.

Upvotes: 0

Related Questions