【问题标题】:Loop a list of text files in same directory and findstr "keyword" in the txt file (batch script)循环同一目录中的文本文件列表并在txt文件中findstr“关键字”(批处理脚本)
【发布时间】:2017-04-03 07:25:10
【问题描述】:

我想创建一个脚本,循环遍历同一目录中的所有.txt 文件并搜索keyword

如果找到keyword,则将filename.txtkeyword found 回显到temp.txt
否则将filename.txtkeyword not found 回显到temp.txt

当前代码:

for /r D:\Users\hi\Documents\bat_for_random %%X in (*.txt) 
findstr "HELLO KEYWORD " %%X &&
(
echo "keyword found" %%X  >temp.txt
)
|| (
echo "keyword not found" %%X  >temp.txt
)
pause

【问题讨论】:

    标签: loops batch-file scripting


    【解决方案1】:

    您的for 语法错误,缺少do 关键字。另外,你把&&/||和括号放错了,需要放在一行。最后,每次循环迭代时,您的重定向运算符> 都会覆盖文本文件temp.txt;使用 >> 代替将附加到文本文件;或者,更好的是,您可以只重定向所有行一次。所以这里是改进的代码:

    > "temp.txt" (
        for /R "D:\Users\hi\Documents\bat_for_random" %%X in ("*.txt") do (
            > nul findstr /C:"HELLO KEYWORD " "%%~X" && (
                echo keyword found "%%~nxX"
            ) || (
                echo keyword not found "%%~nxX"
            )
        )
    )
    

    【讨论】:

      【解决方案2】:

      没有必要有两个列表,一个包含匹配项,一个不包含。在现实世界中,你需要一个或另一个。

      要获得字符串匹配的文件列表是一个命令行,(不需要For循环等)

      FindStr/SMC:"HELLO KEYWORD " "D:\Users\hi\Documents\bat_for_random\*.txt">"temp.txt"
      

      【讨论】:

      • 请问我想在同一个文件中比较两个匹配项,例如“Hello KEYWORD”和“BYE KEYWORD”。两个关键字可能不需要在同一行文本中,但都在同一个 .txt 文件中
      猜你喜欢
      • 2017-08-30
      • 2011-06-07
      • 2023-04-02
      • 1970-01-01
      • 2013-04-11
      • 2015-11-02
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多