0

目前我检查文本文件是否已被修改,如果没有,则重新检查,否则输入文件内容。

我试图做的是在输入文件内容之后,存储一个包含该文件内容的临时变量,并仅在文件被修改时才回显它。

我试图实现的是从文本文件中获取内容,将其输入到控制台,并在修改文件时附加来自文本文件的新内容。我如何实现这一目标?

这是我的代码

@ECHO OFF &setlocal

set currentDate=%date%
SET File=run.txt

:check
FOR %%f IN (%File%) DO SET filedatetime=%%~tf
IF %filedatetime:~0, 10% == %currentDate% goto same

goto notsame

:same
goto next

:notsame
type %File%
for /f "tokens=*" %%A in (%File%) do (echo %%A)

:next
TIMEOUT /T 1 >nul
goto check

echo.
pause

4

2 回答 2

1

有一个“存档属性”。每当 Windows 更改文件时,它都会设置此属性。我们可以在这里使用它:

@ECHO OFF &setlocal
SET "File=run.txt"

:check
timeout 1 >nul
attrib "%file%"|findstr /b "A" >nul || goto :check
REM attribute has changed, so the file has.
type "%file%"
attrib -A "%file%"  &REM remove the archive attribute
goto :check

如果您只想显示新行​​,则需要更多代码(获取行数):

@ECHO OFF &setlocal
SET "File=run.txt"
set "lines=0"

:check
timeout 1 >nul
attrib "%file%"|findstr /b "A" >nul || goto :check
more +%lines% "%file%"
attrib -A "%file%"  &REM remove the archive attribute
for /f %%a in ('type "%file%"^|find /c /v ""') do set "lines=%%a"
goto :check
于 2021-01-14T09:29:02.643 回答
0

我的想法取决于谁访问数据,以及什么时候添加:/。肯定有人会有更好的选择,但是如果您只想要新添加到 run.txt 中的内容,这是我的想法。

NOTE set /p只会抓取第一行。因此,假设在将文件重新创建为空时一次只输入一个完整的行,那么下面应该可以工作。如您所知,您的 for 循环只会抓取最后一行。

REM Still get first line if there is one
set /p prior_content=<Run.txt

REM Create new run.txt file that will be empty for new content
break>run.txt

REM after your date check of course
:notsame

REM Get new content from the empty run.txt that was created at the beginning
set /p new_content=<Run.txt

REM Echo it to CMD
ECHO %new_content%

REM Output to a log file
(
echo %new_content%
echo.
)>>Run_log.txt

我过去的做法有所不同,但我相信这将取决于您的需要。如果不是,我相信会有更聪明的人出现并纠正我的错误。

如果这是一个时间敏感文件,我还建议记录更改时间的时间戳。您正在执行 1 秒的超时,但只检查 10 个字符的日期,因此您每天只会看到一次文件中的更改。我相信你知道,但以防万一你不知道。

编辑

正如评论中提到的,我最初没有包含(并记住我自己)set /p contents=<run.txt只会拉出文本文件的第一行。

我已经改变了我半脑筋的解决方案来反映这个事实。:D

于 2021-01-14T09:28:21.677 回答