当前位置: 动力学知识库 > 问答 > 编程问答 >

windows - remove the directory from output in batchfile

问题描述:

I have the below batchfile that output ReadFile.txt file

cd /d "T:\EMP\SST"

for /r %%i in (T:\EMP\SST) do echo %%i >>D:\MultiThreading\ReadFile.txt

pause

this ReadFile.txt file output

T:\EMP\SST\T:\EMP\SST

T:\EMP\SST\file 11\T:\EMP\SST

T:\EMP\SST\file 12\T:\EMP\SST

T:\EMP\SST\file 13\T:\EMP\SST

I want to remove the directory ouptput T:\EMP\SST so I want my output to be like this

file 11

file 12

file 13

how to do this

网友答案:

you're using FOR in a wrong way. The pattern between the parentheses isn't the start directory, it is the file/directory pattern you want to match. Here I suppose you want *.*

If you only want the filenames (no paths at all) you can write:

@echo off
for /r T:\EMP\SST %%i in (*.*) do echo %%~nxi>>D:\MultiThreading\ReadFile.txt

If you want the filenames + relative paths, it's slightly more complicated but doable, by enabling delayed expansion to be able to remove the path prefix + backslash:

@echo off
setlocal enabledelayedexpansion

set start_path=T:\EMP\SST
for /r %start_path% %%i in (*.*) do (
set f=%%i
echo !f:%start_path%\=!>>D:\MultiThreading\ReadFile.txt
)

This FOR command is cryptic and I have to read the help (FOR /?) everytime, but the fact is: everything useful is in there so I do it all the time :)

网友答案:

I believe you actually need for /D rather than for /R for your task (because I assume file 11, file 12, file 13 are actually directories as they are enumerated by for /R):

for /D %%I in (T:\EMP\SST\*) do echo %%~nxI

Anyway, your for /R syntax is wrong; the directory you want to enumerate recursively needs to be stated immediately after the /R switch (if you omit it, the current directory is assumed), and you need to provide a set (that is the part in between parentheses) that constitutes a pure file name pattern only, without any (absolute or relative) paths, like *.*, for example, to match all files.

In your code, for /R enumerates the current directory. Since your set is T:\EMP\SST and contains no wildcards (*, ?), it is just appended to the enumerated directories literally, because for accesses the file system only in case wildcards are encountered. That explains your weird output.

分享给朋友:
您可能感兴趣的文章:
随机阅读: