将文件读入变量 [英] Read file into variables
问题描述
我需要以批处理代码解析文件.我的文件中有两条信息.
I need to parse a file in batch code. I have two pieces of information in the file.
- 完全合格的源目录(即//server/share/folder)
- 完全合格的目标目录
这些分别记录在文件中.
These are written to the file on seperate lines.
在批处理脚本中,我需要读取文件并将两行放入两个不同的变量(src_dir,tgt_dir).如果使用制表符或分隔符会更好,那么我可以毫无问题地更改定界符.
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.
我正在阅读使用for /f etc
的方法,但是我不知道它是如何工作的.
谢谢您的指点.
I am reading up on using for /f etc
but I don't understand how it works.
Thank you for your pointers.
推荐答案
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%
在for
中,/f
表示将要处理文件内容或命令输出.
In for
, /f
indicates that a file content or command output is going to be processed.
tokens=*
向for
命令指示不应在行上进行拆分.
tokens=*
indicates to for
command that no splitting on the line should be done.
usebackq
向for
命令指示反引号字符串是要执行的命令,而引号字符串是要读取的文件.
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.
这篇关于将文件读入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!