文本文件中棘手的变量设置

问题描述 投票:0回答:1

我有一个 Windows 批处理文件,它读取文本文件的各个行进行处理。在执行过程中,我必须打开另一个只有一行的文本文件。该行包含一个序列号,末尾后有大约 3 或 4 个空格。

我需要读取这个名为(value.txt)的文件,抓取第一行中的数据并将该值分配给一个变量,末尾不带任何空格。 之后,我需要将 .pdf 扩展名添加到该变量并设置为另一个变量。

然后我需要检查当前目录中是否存在具有 pdf 扩展名的变量作为文件名。如果是这样,我可以更改变量值以在 .pdf 之前添加 -1 。如果该文件仍然存在,则尝试 -2 等。 因此 读入的文件名叫做value.txt

55400TERM1(变量 VAR1 分配时不带空格)

55400TERM1.pdf(变量 VAR2 设置为 .pdf 扩展名)

55400TERM1-1.pdf(如果 55400TERM.pdf 存在,则更新变量 VAR2)

55400TERM1-2.pdf(如果 55400TERM1.pdf 存在,则更新变量 VAR2)

等等 - 循环直到无法使用变量值归档现有文件。

variables batch-file set trim spaces
1个回答
0
投票

这是此任务的评论批处理脚本:

@echo off
rem If text file with file name does not exist in current
rem directory, exit this batch file as nothing can be done.
if not exist value.txt (
    echo %~f0: Missing file "value.txt" in "%CD%".
    exit /B
)

rem Read first line from text file. Command FOR automatically splits up the
rem line into strings using space and horizontal tab character as string
rem delimiter. As the line contains just one string with trailing spaces
rem most likely caused by wrong redirecting an output into the text file
rem the single string is assigned to the variable with no trailing spaces.
for /F %%I in (value.txt) do (
    set "FileName=%%I"
    goto CheckFile
)

echo %~f0: No string in file "value.txt" in "%CD%".
exit /B

:CheckFile
if exist "%FileName%.pdf" goto FindLatestFile
echo No file "%FileName%.pdf" found in "%CD%".
set "FileName=%FileName%.pdf"
goto ProcessFile

rem The command DIR as used here lists all files matching the wildcard
rem specification in reverse order according to last modification date.
rem This batch file assumes that the file with highest number is the
rem newest modified file. This speeds up determining the file with the
rem highest number in file name. For an alphabetical reverse order it
rem would be necessary that all files have the same number of digits,
rem i.e. the files are *-01.pdf, *-02.pdf, ..., *-10.pdf, *-11.pdf as
rem otherwise the alphabetical order would be *-1.pdf, *-10.pdf, *-11.pdf,
rem *-2.pdf, ..., *-9.pdf and then last file would be determined wrong.

:FindLatestFile
for /F %%I in ('dir /O-D /TW /B "%FileName%-*.pdf" 2^>nul') do (
    set "LastFileName=%%~nI"
    goto FoundLatestFile
)

echo No file "%FileName%-*.pdf" found in "%CD%".
set "FileName=%FileName%-1.pdf"
goto ProcessFile

:FoundLatestFile
for /F "tokens=2 delims=-" %%I in ("%LastFileName%") do set "LastFileNumber=%%I"
set /A LastFileNumber+=1
set "FileName=%FileName%-%LastFileNumber%.pdf"

:ProcessFile
echo Next file is: %FileName%

要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。

  • dir /?
  • exit /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
© www.soinside.com 2019 - 2024. All rights reserved.