【问题标题】:get multiple strings from .txt then output toghether从 .text 获取多个字符串,然后一起输出
【发布时间】:2021-11-21 20:18:54
【问题描述】:

我有一个带有此文本的 test.txt:

<game>16t (Japan)</game>
<manufacturer>Sega</manufacturer>
<game>3 Ninjas Kick Back</game>
<manufacturer>Malibu</manufacturer>

我正在尝试编写一个批处理文件,它将提取的字符串输出到另一个具有以下模式的 .txt:

game: 16t (Japan)
developer: Sega

game: 3 Ninjas Kick Back
developer: Malibu

我的代码:

@echo off
for /F "tokens=2 delims=>" %%a in ('findstr "<game>" test.txt') do echo game: %%a >> "%~dp0/output.txt"
for /F "tokens=2 delims=>" %%b in ('findstr "<manufacturer>" test.txt') do echo developer: %%b >> "%~dp0/output.txt"

但是我生成的 output.txt 是这样的:

game: 16t (Japan) 
game: 3 Ninjas Kick Back 
developer: Sega
developer: Malibu 

如何实现预期的输出模式?

【问题讨论】:

  • 可以选择 awk 吗?
  • awk 仅默认存在于 Linux 机器上。如果你试图在 Windows 机器上走这条路,那你会很糟糕。
  • 是的,我就是这么想的。不确定。我也安装了Linux。不妨试试看。谢谢。
  • findstr 命令只搜索字符串并返回包含匹配项的行,它无法更改文本行……
  • findstr 命令一次可以搜索多个字符串。了解这些信息并使用正确数量的标记和分隔符后,您可以使用 IF 命令来确定找到的搜索字符串并相应地输出行。

标签: for-loop batch-file


【解决方案1】:

正如 Squashman 在 their comment 中提到的,根据您作为输入文件内容提交的确切格式,有一种更简单的方法:

单行示例

@(For /F "Tokens=1-2 Delims=<>" %%G In ('%SystemRoot%\System32\findstr.exe /IR "<Game> <Manufacturer>" "test.txt" 2^>NUL') Do @If /I "%%G" == "manufacturer" (Echo %%G: %%H& Echo() Else Echo %%G: %%H) 1>"%~dp0output.txt"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多