CMD get string from file and SET it as a variable

2019-04-30 19:43发布

问题:

I'm new to batch files and I'm trying to write one to do part of my work (I know lazy right)

So far I have the following...

SET skip=1

REM for all the directories indicated to contain core repositories
FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO ( 
SET TgtDir =%%i
echo %TgtDir% >> C:\result.txt
)

The contents of Repos.txt is:

60000
C:\somedir\someotherdir\
C:\a\b\c\

Basically I want this script to go through a file, ignoring the first line which will be used for a delay setting later, and extract each line then (ideally) pass it to a cd command but for now I'm just trying to get it into the variable TgtDir.

When i run this script the output in C:\result.txt is:

ECHO is on.
ECHO is on.

Any help?

回答1:

You'll want to look at the EnableDelayedExpansion option for batch files. From the aforementioned link:

Delayed variable expansion is often useful when working with FOR Loops. Normally, an entire FOR loop is evaluated as a single command even if it spans multiple lines of a batch script.

So your script would end up looking like this:

@echo off
setlocal enabledelayedexpansion
SET skip=1

REM for all the directories indicated to contain core repositories
FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO (
    SET TgtDir=%%i
    echo !TgtDir! >> C:\result.txt
)

As an alternative, just use the %%i variable in your inner loop, rather than creating a new variable.



回答2:

@echo off
setlocal enabledelayedexpansion
SET skip=1
REM for all the directories indicated to contain core repositories
FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO echo %%n>>c:result.txt