简体   繁体   中英

Batch File to read 'N' characters from a text file

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.

I want to pull only a few characters from the line.

Eg: 12345qwerty67890

If this on in a text file i want to pull only '12345' and assign it to a variable.

Any help is greatly appreciated.

set HELP SET and try the following to get you started

@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in (sample.txt) do (
  set line=%%a
  set chars=!line:~0,5!
  echo !chars! --- !line!
)

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM