1

I am working with a batch file that monitors a folder and looks to see if there are any files. I do not know much about batch programming and inherited the file, but could anyone let me know if there is a way were I can read in the filename and trim a certain amount of characters from it?

The filename is always going to look like this: 12345_20131031.txt There will also be 8 characters to the right of the _ and, plus 4 characters for the ".txt"

I basically just want to grab the filename and trim everything to the right of the "_" and the extension so I am just left with: 12345

Below is the code I have for looping through the files. I have been following around with what is already there, but all I can seem to get is the full path/dir/filename of the file and I can't seem to get the right setting to just give me the filename and trim it.

Any help would be appreciated:

@ECHO OFF


set cnt= for %%a in (c:\Encoded_HL7_Vanderbilt\*.*) do set cnt=%%a

if !%cnt%!==!! exit

set "folder=%~1"


:: If more than 0 files exist begin, otherwise exit
FOR %%a IN (c:\Encoded_HL7_Vanderbilt_rob\*.*) DO (


:: need to get filename and trim everything to the right of "_" here

)

exit

:done 
goto :EOF
4

2 回答 2

1

此示例显示如何仅获取文件名%%~nA,然后通过_下划线对其进行解析。

@echo off
pushd "c:\Encoded_HL7_Vanderbilt_rob\"
for %%A in (*.*) do for /f "delims=_" %%B in ("%%~nA") do echo %%B
popd
于 2013-11-05T20:13:20.743 回答
1

以下将循环遍历 c:\Encoded_HL7_Vanderbilt_rob\ 的目录列表,并回显文件名中_之前的所有内容。将 /a:-d 与 dir 一起使用将使其不显示目录。

for /f "delims=_" %%A in ('dir /b /a:-d c:\Encoded_HL7_Vanderbilt_rob\') do (
     echo %%A
     REM %%A will be the the first part of the file name.
)
于 2013-11-06T00:04:21.857 回答