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

问题描述 投票:0回答:1

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

这是我的命令:

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

显示输出的示例是:

lastServer:111.111.111.111:53680

如何从输出行中获取不包含字符串

lastServer:
的 5 个数字(IP 地址和端口号)?

batch-file findstr
1个回答
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 /?
© www.soinside.com 2019 - 2024. All rights reserved.