获取存储在文本文件中的值并将其转换为变量

时间:2018-12-02 21:20:21

标签: batch-file

我有一个看起来像这样的文本文件:

0_1 100 102 20 278 28 32 20 102 0_2 823 72 182 182 938 2739 182 162 0_3 3873 1728 

有一个模式,0_1、0_2、0_3,继续到0_10,甚至更高(9个块)。我想把每个数字变成一个变量。我正在使用以下代码来执行此操作(文件名calc_.cmd):

for /F "tokens=%1-%2" %%a in (%4) do (
    set "tick_%3=%%a"
    set "val1_%3=%%b"
    set "val2_%3=%%c"
    set "val3_%3=%%d"
    set "val4_%3=%%e"
    set "val5_%3=%%f"
    set "val6_%3=%%g"
    set "val7_%3=%%h"
    set "val8_%3=%%i"
)

像这样执行它:

call calc_.cmd 1 9 1 %1
call calc_.cmd 10 18 2 %1
call calc_.cmd 19 27 3 %1
call calc_.cmd 28 36 4 %1

%1是文本文件。继续..

echo %val8_1%返回:102。但echo %val8_4%返回ECHO is on.

我假设这与范围不能超过26有关,但是%val8_3%确实返回了正确的值。我想知道是否还有其他方法可以解决此问题,或者我做错了,我很高兴听到!欢呼

1 个答案:

答案 0 :(得分:0)

问题的说明有些令人困惑...无论如何,这是一个可行的解决方案:

@echo off
setlocal EnableDelayedExpansion

rem %1 = Number of starting element in input list (tick_%3) of group %3
rem %2 = Number of ending element in input list (val8_%3) of group %3
rem %3 = Group
rem %4 = Input file

set /A "start=%1-1, end=%2-%1, n=0"
for /F "delims=" %%a in (%4) do (
   for %%b in (%%a) do (
      if !start! gtr 0 (
         set /A start-=1
      ) else if !n! leq %end% (
         if !n! equ 0 (
            set "tick_%3=%%b"
         ) else (
            set "val!n!_%3=%%b"
         )
         set /A n+=1
      )
   )
)

SET TICK
SET VAL

输出示例:

> calc_.bat 1 9 1 file.txt
tick_1=0_1
val1_1=100
val2_1=102
val3_1=20
val4_1=278
val5_1=28
val6_1=32
val7_1=20
val8_1=102

> calc_.bat 10 18 2 file.txt
tick_2=0_2
val1_2=823
val2_2=72
val3_2=182
val4_2=182
val5_2=938
val6_2=2739
val7_2=182
val8_2=162

您应该注意,您的输入数据是多余的。如果开始和结束元素是9的倍数,并且始终取决于组的数目,则不需要它们,因为可以从组号计算得出。这一点还允许使用其他更简单的方法:

@echo off
setlocal EnableDelayedExpansion

rem %1 = Group
rem %2 = Input file

for /F "delims=" %%a in (%2) do set "input=%%a"

for /L %%i in (2,1,%1) do for /F "tokens=1-9*" %%a in ("!input!") do set "input=%%j"

for /F "tokens=1-9" %%a in ("%input%") do (
    set "tick_%1=%%a"
    set "val1_%1=%%b"
    set "val2_%1=%%c"
    set "val3_%1=%%d"
    set "val4_%1=%%e"
    set "val5_%1=%%f"
    set "val6_%1=%%g"
    set "val7_%1=%%h"
    set "val8_%1=%%i"
)

SET TICK
SET VAL

输出示例:

> calc_2.bat 1 file.txt
tick_1=0_1
val1_1=100
val2_1=102
val3_1=20
val4_1=278
val5_1=28
val6_1=32
val7_1=20
val8_1=102

> calc_2.bat 2 file.txt
tick_2=0_2
val1_2=823
val2_2=72
val3_2=182
val4_2=182
val5_2=938
val6_2=2739
val7_2=182
val8_2=162