Read file into variables

2020-05-03 10:43发布

问题:

I need to parse a file in batch code. I have two pieces of information in the file.

  • Fully qualified source directory (i.e. //server/share/folder)
  • Fully qualified target directory

These are written to the file on seperate lines.

In my batch script, I need to read the file and put both lines into two different variables (src_dir, tgt_dir). I can change the delimiter without a problem if tabbed or spaced would be better.

I am reading up on using for /f etc but I don't understand how it works. Thank you for your pointers.

回答1:

set "src_dir="
set "tgt_dir="
for /f "tokens=* usebackq" %%a in ("c:\somewhere\myfile.txt") do (
  if not defined src_dir ( 
    set "src_dir=%%~a" 
  ) else if not defined tgt_dir (
    set "tgt_dir=%%~a"
  )
)
echo %src_dir%
echo %tgt_dir%

In for, /f indicates that a file content or command output is going to be processed.

tokens=* indicates to for command that no splitting on the line should be done.

usebackq indicates to for command that backquoted strings are a command to execute, and quoted string is a file to be read.

For each line readed, the code in parenthesis is executed, determining which of the two variables should receive the readed value.



回答2:

FOR /F is not the best option in this case. I would solve the problem as follows:

<"yourFile.txt" (
  set /p "src_dir="
  set /p "tgt_dir="
)

:: Show result
echo src_dir=%src_dir%
echo tgt_dir=%tgt_dir%

If you have empty lines between the values, then you must add an additional set /p = for each empty line so that it gets skipped.


One disadvantage of both this method and the MC ND solution is that the values must be in a particular order. If you have control over the creation of the data file, then you can create a simpler and more robust solution.

Simply prefex each value with varname=. For example, your data file code look like

src_dir=path1
tgt_dir=path2

Then you can use the following very simple script to read in the values. The script does not have to change if you add additional variables.

for /f "usebackq delims=" %%A in ("pathSpecForYourDataFile") do set "%%A"


回答3:

What you need to do is parse the batch code, and read them into your 2 variables