使用批处理脚本读取和写入整数到文本文件

时间:2018-06-05 13:16:04

标签: batch-file

我有以下批处理脚本:

@echo off
if exist test.txt (
    set /p foo=<test.txt
    echo "read: %foo%"
    set /A foo=foo+1
    (echo %foo%)>test.txt
    echo "wrote: %foo%"
) else (
    (echo 1)>test.txt
)

我希望脚本检查文件test.txt是否存在。如果该文件不存在,则脚本应将1写入该文件。如果文件确实存在,脚本应该从文件读取值,将其递增1,然后写回增量文件。

我希望我的输出看起来像这样:

C:\opt>test.bat

C:\opt>test.bat
"read: 1"
"wrote: 2"

C:\opt>test.bat
"read: 2"
"wrote: 3"

C:\opt>test.bat
"read: 3"
"wrote: 4"

但是我得到以下输出:

C:\opt>test.bat

C:\opt>test.bat
"read: 2"
"wrote: 2"

C:\opt>test.bat
"read: 2"
"wrote: 2"

C:\opt>test.bat
"read: 3"
"wrote: 3"

C:\opt>test.bat
"read: 3"
"wrote: 3"

C:\opt>test.bat
"read: 4"
"wrote: 4"

C:\opt>test.bat
"read: 4"
"wrote: 4"

为什么变量foo似乎没有按预期增加?

2 个答案:

答案 0 :(得分:2)

您需要使用延迟变量扩展,以便从计算中获取当前值:

@echo off
setlocal enabledelayedexpansion
if exist test.txt (
    set /p foo=<test.txt
    echo "read: !foo!"
    set /A foo=foo+1
    (echo !foo!)>test.txt
    echo "wrote: !foo!"
) else (
    (echo 1)>test.txt
)

答案 1 :(得分:0)

您的代码可以简化。

如果先将变量设置为零,然后使用SET /P和重定向读取文本文件,它将覆盖变量。无论变量处于什么状态,您都可以在此时添加1。

@echo off
set "foo=0"
IF exist "test.txt" set /p foo=<test.txt
echo read: %foo%
set /A "foo+=1"
echo wrote: %foo%
>test.txt echo %foo%

你甚至可以摆脱IF EXIST,只是在文件不存在时将错误重定向到nul。

@echo off
set "foo=0"
(set /p foo=<test.txt)2>nul
echo read: %foo%
set /A "foo+=1"
echo wrote: %foo%
>test.txt echo %foo%