DOS批处理命令从文本文件读取一些信息
我正在尝试使用Windows命令行从文本文件中读取一些信息,并将其保存到一个变量中,就像“set info =1234”
下面是txt文件的内容,实际上我只需要修订号和它的位置始终是相同的第 5 行,从第 11 列到第 15 列。在示例中它是 1234,我想知道是否有一种方法可以将它保存到 Dos 命令行中的变量中。
多谢!
svninfo.txt:
Path: .
URL: https://www.abc.com
Repository Root: https://www.abc.com/svn
Repository UUID: 12345678-8b61-fa43-97dc-123456789
Revision: 1234
Node Kind: directory
Schedule: normal
Last Changed Author: abc
Last Changed Rev: 1234
Last Changed Date: 2010-04-01 18:19:54 -0700 (Thu, 01 Apr 2010)
I am trying to read some info from a text file by using windows command line, and save it to a variable just like "set info =1234"
Below is the content of the txt file, actually I just need the revision number, and the location of it is always the same line 5, and from column 11 to 15. In the sample it's 1234, and I am wondering is there a way to save it to a variable in Dos command line.
Thanks a lot!
svninfo.txt:
Path: .
URL: https://www.abc.com
Repository Root: https://www.abc.com/svn
Repository UUID: 12345678-8b61-fa43-97dc-123456789
Revision: 1234
Node Kind: directory
Schedule: normal
Last Changed Author: abc
Last Changed Rev: 1234
Last Changed Date: 2010-04-01 18:19:54 -0700 (Thu, 01 Apr 2010)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个单行版本:
Here's a one line version:
以下代码片段显示了如何执行此操作:
其输出为所需的
1234
。我在每个脚本中使用
setlocal
来确保以已知的方式处理变量。for
语句处理输入文件中的每一行(delims
位阻止该行被标记为单独的单词)。!line:~
位是子字符串,其中!line:~0,10!
是前十个字符,!line:~10!
是其余的。因此,基本上,它会检查每一行是否以
"Revision: "
开头,如果是,则提取该行的其余部分供以后使用。The following code snippet shows how to do this:
Its output is
1234
as desired.The
setlocal
is what I use in every script to ensure variables are treated in a known way. Thefor
statement processes each line in the input file (thedelims
bit stops the line from being tokenised into separate words).The
!line:~
bits are substrings with!line:~0,10!
being the first ten characters and!line:~10!
being the rest.So, basically, it checks every line to see if it starts with
"Revision: "
and, if so, extracts the rest of the line for later.使用
for
命令解析文件:Use the
for
command to parse the file:如果您有可以使用 GNU 工具,例如 gawk
if you have can use GNU tools, such as gawk
知道如何熟练地使用 CMD 脚本固然很棒,但使用 PowerShell 就更好了。这是一种方法:
发生了什么?
$revision
是一个变量gc
是Get-Content
,又名类型
。文件中的每一行都成为序列(管道)中的一个字符串。?
是Where-Object
。它根据条件过滤管道中的对象。{}
分隔脚本块$_
是管道中的当前对象。的对象
[1]
索引-split
调用 .NET 中的String.Split()
,为您提供数组中Knowing how to use CMD scripting deftly is great, but using PowerShell is even better. Here's one way to do it:
What's going on?
$revision
is a variablegc
isGet-Content
, akatype
. Each line in the file becomes a string in a sequence (pipeline).?
isWhere-Object
. It filters the objects in a pipeline based on a condition.{}
delimits a script block$_
is the current object in the pipeline.-split
invokesString.Split()
in .NET, giving you an array of objects[1]
indexes in to the array