首页 > 解决方案 > 将括号之间的输出保存到新的 txt 文件的批处理文件

问题描述

我正在运行以下批处理脚本以从 IP 反向查找域名

对于 /f %%i in (c:\ip.txt) 做 (Ping -a %%i -n 1 >>output.txt )

文件 ip.txt 中有一个 IP 列表。

输出文件有这样的输出,这是预期的

Pinging UKSEVRERNAME.com [10.87.130.200] with 32 bytes of data:
Reply from 10.87.130.200: bytes=32 time=16ms TTL=53

Ping statistics for 10.87.130.200:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 16ms, Maximum = 16ms, Average = 16ms

我想要的是只保留服务器名称和IP,而忽略其余的......

有什么建议么?

标签: batch-file

解决方案


注意力。以下代码取决于语言:

For /f %%i in (ip.txt) do (
  for /f "tokens=2" %%a in ('Ping -a %%i -n 1^|find "["') do echo %%a  %%i
)

这适用于英文 Windows 版本 ( Pinging <Server> [<IP>] with 32 bytes of data:)

你必须适应tokens你的本地化。例如,德国 Windows 提供
Ping wird ausgeführt für <Server> [<IP>] mit 32 Bytes Daten:,所以它会是tokens=5

如果无法解析主机名,则此代码不会为此主机提供任何结果。

如果您想使用 IP,请将find字符串更改为find " 32 "(注意空格)


推荐阅读