Phil
Phil

Reputation: 31

How to remove new line from text file in for loop (CMD/Batch)

My goal is to use a text file created by a for loop as an input for a variable to another for loop. However, the initial text file created has a new line/space at the end, and is being declared as a variable when reading said text file.

Code below is creating a text file...

for /F "Skip=1 Delims=:" %%A In ('WMIC LogicalDisk Get Caption') do @echo(%%A>> "EXAMPLE DIRECTORY\partitions.txt"

This text output file then looks like

A
C
D
(empty line)

I am then using this text file to feed into another for command for which each of these lines are used as a variable.

for /F "delims=" %%P in (EXAMPLE DIRECTORY\partitions.txt) do (echo test.exe -partition %%P

This (empty line) or space is being fed as a variable and it is undesirable so I am looking for a fix somewhere along this chain of commands.

Upvotes: 0

Views: 1125

Answers (2)

Compo
Compo

Reputation: 38579

You could have simply asked in the topic I provided the answer to you.

(For /F "Skip=1 Delims=:" %%A In ('WMIC LogicalDisk Get Caption') Do For %%B In (%%A) Do Echo(%%B:)>"EXAMPLE DIRECTORY\partitions.txt"

Upvotes: 1

MC ND
MC ND

Reputation: 70923

Don't include non needed lines in the output file

>"EXAMPLE DIRECTORY\partitions.txt" (
    for /f "tokens=2 delims==:" %%a in ('
        wmic logicaldisk get caption /value
    ') do (echo(%%a)
)

Asking wmic for the /value format the output will be like

Caption=C:

Using the colon and the equal sign as delimiters we only leave the drive letter and, as we are requesting tokens=2, lines without a second token (the drive letter) are discarded.

Upvotes: 2

Related Questions