windows 批处理文件从文本文件中读取“N”个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8591566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Batch File to read 'N' characters from a text file
提问by Telson Alva
I have searched this across the net and found many codes for retrieving the entire line from a text or replacing the text with another but not for what i was looking for.
我在网上搜索了这个,发现了许多代码,用于从文本中检索整行或用另一个文本替换文本,但不是我正在寻找的。
Using the For loop with the tokens would return on the set (word) separated with spaces.
使用带有标记的 For 循环将返回以空格分隔的集合(单词)。
I want to pull only a few characters from the line.
我只想从行中提取几个字符。
Eg: 12345qwerty67890
例如: 12345qwerty67890
If this on in a text file i want to pull only '12345' and assign it to a variable.
如果在文本文件中打开,我只想提取“12345”并将其分配给变量。
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by PA.
set HELP SET
and try the following to get you started
设置HELP SET
并尝试以下操作以帮助您入门
@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in (sample.txt) do (
set line=%%a
set chars=!line:~0,5!
echo !chars! --- !line!
)
回答by Mike Nakis
At the command prompt, do help set
. There you will find more information about the set
command than you would ever want to know. The part you are interested in says:
在命令提示符下,执行help set
. 在那里,您将找到set
比您想知道的更多的关于该命令的信息。您感兴趣的部分说:
May also specify substrings for an expansion.
%PATH:~10,5%
would expand the PATH environment variable, and then use only the 5
characters that begin at the 11th (offset 10) character of the expanded
result. If the length is not specified, then it defaults to the
remainder of the variable value. If either number (offset or length) is
negative, then the number used is the length of the environment variable
value added to the offset or length specified.
Of course, in order to use that kind of stuff with the for
loop variable, you need to first get acquainted with the very peculiar way in which variables are expanded in Windows NT batch files. Let me know if you have problems with that, and I can add more information.
当然,为了在for
循环变量中使用这种东西,您首先需要熟悉在 Windows NT 批处理文件中扩展变量的非常奇特的方式。如果您对此有疑问,请告诉我,我可以添加更多信息。