问题描述:

I have a folder that contains multiple .txt files. I would like to be able to make a batch file to read those files and assign a variable to each value (each .txt file only contains one number). I have found scripts to read the individual files, but lack the ability to assign a variable to each of them.

网友答案:

You don't say how you want to name your variables. I'll assume you want a variable name that matches the job name. For example, if file is named JOB_123.txt, then the variable would be named JOB_123

for /f "tokens=1* delims=:" %%A in ('findstr "^" job_*.txt') do set "%%A=%%B"

If the job numbers don't matter, and you simply want an array of values, then:

for /f "tokens=1,2* delims=:" %%A in ('findstr "^" job_*.txt^|findstr /n "^"') do set jobCnt=%%A&set "job[%%A]=%%C"

This will create variables named job[1], job[2], etc. And jobCnt will contain the total number of values.

网友答案:

Test this:

@echo off
set c=0
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir *.txt /b /a-d ') do (
set /a c+=1
set /p a[!c!]=<"%%a"
)
set a[
pause
网友答案:
@ECHO Off
SETLOCAL 
SET "sourcedir=U:\sourcedir"
:: remove variables starting JOB
FOR  /F "delims==" %%a In ('set JOB 2^>Nul') DO SET "%%a="

FOR /f "delims=" %%a IN (
  'dir /s /b /a-d "%sourcedir%\job_*.txt" '
  ) DO (
 FOR /f "delims=" %%b IN ('type "%%a"') DO (
  IF DEFINED %%~na (ECHO %%~na repeated) ELSE (SET "%%~na=%%b")
 )
)

SET job

GOTO :EOF

This job should set up variables named job_* containing the data read from each job_*.txt file found in the subtree with root at sourcedir - I used u:\sourcedir which suits my system. You would need to change that to suit yours.

相关阅读:
Top