I want to concatenate the file names taken out by the dir command.

Asked 2 years ago, Updated 2 years ago, 123 views

I would like to use the command prompt to extract the file name and print it out as a list separated by a blank space.
When you use the dir command in a batch file, you get the following results:

>dir/B
A.txt
B.txt
C.txt   

The following script was expected to display a space-separated filename.

@echo off  
for/F%%%A in('dir/B')do(  
    set STR = %STR%%A  
)  
echo "%STR%"

Expected results:

"A.txt B.txt C.txt"

However, the above script does not show anything.
I think the script file is wrong, but I don't know where it's wrong, so please let me know.

windows command-line batch-file

2022-09-30 20:17

3 Answers

An example as it is was written in the SET command help (set/?).

First, turn on the delay environment variable expansion (cmd/V:ON)
Then you can write as follows.

@echo off
set STR =
for /F%%A in('dir/B') do set STR=!STR!%%A
echo "%STR%"

Also, I think the FOR part is simply for %%A in(*)do set STR=!STR!%%A.

However, if you do cmd/V:ON for this reason, the command shell will be nested, and
I think it would be better to use JScript or VBScript.


2022-09-30 20:17

In my environment (Windows 7), the result is "c.txt".

Use the delay environment variable to get the desired result.

@echo off
setlocal enabled delayed expansion
set STR =
for/F%%%A in('dir/B')do(
  set STR=!STR!%%A
)
echo "%STR%"
endlocal

For more information, please refer to the following page.

Batch file.Points to Note when Writing Multiple Commands in IF or FOR Statements - Windows Command Prompt (bat, cmd)-to_dk notebook


2022-09-30 20:17

You have already answered the delay assessment, but there is also a way to use a subroutine.In this case, cmd.exe does not require the /V option to achieve the desired results.

@echo off
set STR =
for/F%%%A in('dir/B')do(
  call —add%%A
)
echo "%STR%"

—add
set STR = %STR%%1


2022-09-30 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.