Windows Batch:读取和更新文件

时间:2015-03-25 15:00:46

标签: batch-file cmd

我不确定,如果标题合适,我很抱歉...... :)

我有一个脚本,需要在文件中保留某种统计信息。

该文件如下:

No of attempts: x
No of failed attempts: y

就是这样。现在,我需要创建一个批处理脚本,它将读取这两个数字并相应地更新它们。

我有以下代码,但它不起作用(惊讶,惊讶)。

@echo off

set statfile=statfile.txt
set tmpfile=tmpfile.txt
set attempts=0
set fattempts=0

if exist %statfile% (
    for /f "tokens=*" %%i in (%statfile%) do (
        echo %%i > %tmpfile%
        if %attempts% equ 0 (
            for /f "tokens=4" %%j in (%tmpfile%) do set /a attempts=%%j+1
        ) else (
            for /f "tokens=5" %%k in (%tmpfile%) do set /a fattempts=%%k+1
        )
    )
)

echo No of attempts: %attempts% > %statfile%
echo No of failed attempts: %fattempts% >> %statfile%

我是批处理的新手,所以我不确定我是否正确理解了令牌。而且我知道这个剧本的逻辑是......好吧,不好,我只是不知道什么是bash提供的,即使我看了,我也找不到真正有用的东西。

提前谢谢!

2 个答案:

答案 0 :(得分:1)

@ECHO OFF

set statfile=statfile.txt
REM I assume these two lines are just for demo?:
set attempts=0
set fattempts=0

if not exist %statfile% goto :error
REM read file (two lines):
<%statfile% (
  set /p att=
  set /p fatt=
)
REM remove anything before and including the colon and add delta:
set /a attn=%att:*:=% + %attempts%
set /a fattn=%fatt:*:=% + %fattempts%

REM write new file:
echo No of attempts: %attn% > %statfile%
echo No of failed attempts: %fattn% >> %statfile%
goto :eof
:error
echo Statfile not found

set newvar=%var:*:=%的解释:(第一个)冒号告诉解释器对变量做了一些事情,*:=是必须要做的事情:从一开始(*)直到应该替换冒号:=) - 在这种情况下没有任何内容。

例如,试试这个:

set "a=This is my string"
echo %a:*my=It's your%

答案 1 :(得分:1)

@ECHO Off
SETLOCAL
SET "statfile=q29529242.txt"
set "attempts="
set "fattempts="
FOR /f "tokens=4,5" %%a IN (%statfile%) DO (
 IF DEFINED attempts (SET /a fattempts=%%b) ELSE (SET /a attempts=%%a)
)
SET /a attempts+=1
REM IF (condition FOR false) SET /a fattempts+=1

echo No of attempts: %attempts% > %statfile%
echo No of failed attempts: %fattempts% >> %statfile%

GOTO :EOF

我使用了一个名为q29529242.txt的文件,其中包含我的测试数据。

注意:

set语句始终适用于字符串。 /a选项解释指定为公式的值,并将结果分配给值。

set "var=value"语法可确保该行上的尾随空格包含在指定的值中。分配空值“删除”变量。请注意,两个方面的空格 很重要。

for /f标记选项使用delims分隔符来解释该行,默认为空格,逗号,分号。文本行被视为由分隔符 - 序列分隔的标记序列。

因此,就行了

No of failed attempts: y
  • 不是令牌1
  • 是令牌2
  • 失败是令牌3
  • 尝试:是令牌4
  • y是令牌5

你设置'delims =:'然后

  • 没有失败的尝试是令牌1
  • “y”(不带引号)是令牌2

(请注意,分隔符本身包含在内)

您可以按编号选择标记,以逗号分隔。特殊标记*表示“在最高指定标记之后的分隔符之后的行中的所有内容”。标记被赋予最低选择的元变量(循环控制变量),然后按数字顺序分配给每个下一个按字母顺序的变量。

请注意,在“块语句”(带括号的系列语句)中,值%var%将替换为变量的初始值。有一些方法可以改变这种行为。然而,if defined语句使用current值(它是否已定义),因为它在循环内变化。

随后,由于attempts最初被清除,因此在读取第一行后,attempts被设置为4令牌(x)。在第二行,attempts现已设置,因此fattempts设置为5令牌(y)。

我使用/a因为该值将是数字,这使得赋值不受空格的影响。

set /?

来自set

的类似C语法的文档提示