如何仅通过findstr命令从文本文件中找到的行中获取最后5个数字?

时间:2015-09-16 03:47:46

标签: batch-file findstr

我想从 txt 文件的显示输出中获取 FindStr 命令的最后5个数字

这是我的命令:

FindStr "lastServer" C:\Users\Defcon1\AppData\Roaming\.minecraft\.options.txt

显示输出的示例是:

lastServer:111.111.111.111:53680

如何从输出行获取没有字符串lastServer:的5个数字(IP地址和端口号)?

1 个答案:

答案 0 :(得分:1)

这是一项非常简单的任务,并且易于编码,例如:

@echo off
setlocal
set "OptionsFile=%APPDATA%\.minecraft\.options.txt"

rem Does the file exist at all?
if not exist "%OptionsFile%" (
    echo Error: File %OptionsFile% not found!
    goto EndBatch
)

rem Search for last server line in file and get IP address and port number.
set "IP_and_Port="
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe "lastServer" "%OptionsFile%" 2^>nul') do set "IP_and_Port=%%J"

rem Was IP and port number found in file?
if "%IP_and_Port%" == "" (
    echo Error: Found in file %OptionsFile%
    echo        no line with string "lastServer" with an IP address and a port number!
    goto EndBatch
)

rem Output found data.
echo Found: %IP_and_Port%

:EndBatch
endlocal
pause

也可以在不使用 findstr 实用程序的情况下工作:

@echo off
setlocal
set "OptionsFile=%APPDATA%\.minecraft\.options.txt"

rem Does the file exist at all?
if not exist "%OptionsFile%" (
    echo Error: File %OptionsFile% not found!
    goto EndBatch
)

rem Search for last server line in file and get IP address and port number.
for /F "usebackq tokens=1* delims=:" %%I in ("%OptionsFile%") do (
    if /I "%%I" == "lastServer" (
        set "IP_and_Port=%%J"
        goto DataFound
    )
)

echo Error: Found in file %OptionsFile%
echo        no line with string "lastServer" with an IP address and a port number!
goto EndBatch

rem Output found data.
:DataFound
echo Found: %IP_and_Port%

:EndBatch
endlocal
pause

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • echo /?
  • endlocal /?
  • findstr /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • rem /?
  • set /?
  • setlocal /?
相关问题