你可以使用我的JREPL.BAT regular expression text processing utility 来创建一个tail 命令。 JREPL.BAT 是纯脚本(混合 JScript/批处理),可以在 XP 以后的任何 Windows 机器上本地运行。
以下命令将显示chat.txt中的最后一行
call jrepl "^.*" "" /match /inc -1 /f chat.txt
但是有一个更好的方法来开发批处理聊天程序(假设这是一个值得的目标)
您可以在循环中进行批处理,将输入重定向到循环外部,并且循环将在新添加的行出现时读取和写入它们。您可以使用 SET /P 和 ECHO,但使用单个 FINDSTR 更简单。这是因为 FINDSTR 在调用时不会重置文件指针,如 http://www.dostips.com/forum/viewtopic.php?p=9720#p9720 中所述。
您应该使用一些命令在显示循环中暂时暂停处理,以防止循环消耗 100% 的 CPU 内核。您可以使用 TIMEOUT 或 PING hack,但它们会引入约 1 秒的延迟。我选择使用 PATHPING 来引入约 0.2 秒的延迟。
此外,如果两个进程同时写入同一个文本文件,您必须担心防止冲突。这可以通过使用锁定文件来解决,如How do you have shared log files under Windows? 所述。
下面是一个基本的批处理聊天程序的开始。它的工作原理是让两个或多个用户各自导航到同一个共享目录,然后运行chat.bat sessionName,其中 sessionName 是共享聊天文件的商定名称。每个用户都会在他们的主控制台窗口中看到共享聊天对话框,并且会打开一个新的控制台窗口,他们可以在其中写下他们对对话的贡献。输入:quit退出聊天程序。
@echo off
setlocal disableDelayedExpansion
if "%~1" equ ":input" goto :startInput
if "%~1" equ ":display" goto :display
set "base=%~1"
set "dialog=%base%.chat"
set "quitfile=%base%_%username%.chat.quit"
start "" "%~f0" :input
del "%quitfile%" 2>nul
cmd /c "%~f0" :display
del "%quitfile%" 2>nul
exit /b
:display
title Chat Dialog
set "quit="
if not exist "%dialog%" (call ) >>"%dialog%"
<"%dialog%" ( for /l %%N in () do (
if exist "%quitfile%" set "quit=1"
findstr "^"
if defined quit exit
pathping -p 150 -q 2 localhost >nul
))
:startInput
setlocal enableDelayedExpansion
title Chat Input
call :write ">>> %username% has joined the conversation"
:input
cls
set "text="
set /p "text=>"
if /i !text! equ :quit (
call :write "<<< %username% has left the conversation"
copy nul "!quitfile!"
exit
)
call :write
goto :input
:write
if "%~1" neq "" (set "text=%~1") else (set "text=%username%: !text!")
2>nul (
>>"!dialog!" (
echo(!text!
(call )
) || goto :write
)
exit /b
还有待完成:
- 提供一种邀请用户聊天的机制。
- 提供在新聊天会话开始时清除聊天内容的选项(以防旧会话名称被重用)
- 提供 :list 命令列出当前参与的用户。这将需要创建 sessionNameUserId 文件,只要用户仍在收听和/或参与,这些文件就会保持锁定状态。显示循环可以通过文件接收 :list 命令,与我实现 :quit 的方式相同,然后它可以尝试打开每个 sessionNameuserID 文件进行写入。如果失败,则用户仍然处于活动状态,并且应该列出名称。
- 我相信还有其他可能有用的东西。