如何在Windows命令脚本中将数字添加到文件中现有行的末尾

时间:2017-04-20 14:01:29

标签: windows batch-file

尝试将数字添加到文件行的末尾,如下所示:

Id
CN04FIL002,21,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 10:32,
CN04FIL002,365,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 10:35,
CN04FIL002,3285,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 10:44,
CN04FIL002,9318,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 10:59,
CN04FIL002,3,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 11:01,
CN04FIL002,2373,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 11:29,
CN04FIL002,2684,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 11:10,
CN04FIL002,26,,,cn04fil002.mhf.mhc,1,backupexec,03/30/2017 10:30,03/30/2017 10:30,03/30/2017 11:23,

等等。我想要做的是编写一个脚本,在每行的最后一个逗号后添加递增数字,并保存当前数字,以便每次运行脚本时数字都可以继续增加。我该如何做这样的事情?

2 个答案:

答案 0 :(得分:0)

以下代码可以满足您的需求。

@echo off

setlocal EnableDelayedExpansion

for /f %%i in (count.txt) do (
    set "linesCount=%%i"
)

set "numLine=0"
for /f "tokens=*" %%i in (file.txt) do (
    set /a "numLine+=1"
    if "!linesCount!" equ "0" (
       echo(%%i!numLine!>>file.new.txt 
    ) else (
       set /a "linesCount-=1"
       echo(%%i>>file.new.txt
    )
)

move /Y file.new.txt file.txt >nul 2>&1
echo(!numLine!>count.txt

我在一个名为count.txt的文件中保存了上次处理的行数。如果它不存在,也就是说,脚本从未运行过create count.txt,内部为零。只需将file.txt重命名为您的文件名。

答案 1 :(得分:0)

我认为这可能是最快的方法:

@echo off
set "_FILE=textfile.txt"

for /F %%C in ('^< "%_FILE%" find /C /V ""') do set "COUNT=%%C"
< "%_FILE%" (
    setlocal EnableDelayedExpansion
    for /L %%I in (1,1,%COUNT%) do (
        set /A "INDEX=%%I-1"
        set "LINE=" & set /P LINE=""
        if !INDEX! GTR 0 (
            echo(!LINE!!INDEX!
        ) else (
            echo(!LINE!
        )
    )
    endlocal
)

这会跳过被认为是标题的第一行(Id) 附加的第一个索引号是1