Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMD get string from file and SET it as a variable to use in cd

Tags:

batch-file

cmd

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?

like image 267
Richard Newman Avatar asked Sep 20 '12 13:09

Richard Newman


People also ask

What is %% A in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What does @echo off do?

The ECHO-ON and ECHO-OFF commands are used to enable and disable the echoing, or displaying on the screen, of characters entered at the keyboard. If echoing is disabled, input will not appear on the terminal screen as it is typed. By default, echoing is enabled.

How do I echo a variable in CMD?

Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable. For example, to check if NUKE_DISK_CACHE is set, enter echo %NUKE_DISK_CACHE%.


1 Answers

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.

like image 184
Jonah Bishop Avatar answered Oct 06 '22 21:10

Jonah Bishop