将文件读入变量 [英] Read file into variables

查看:104
本文介绍了将文件读入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以批处理代码解析文件.我的文件中有两条信息.

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.

usebackqfor命令指示反引号字符串是要执行的命令,而引号字符串是要读取的文件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆