繁体   English   中英

GREP 相当于 Windows OS 通过 Python 脚本

[英]GREP equivalent for Windows OS through Python script

拜托,有人可以帮我用以下命令替代 Windows 吗:

Linux 版本:找到 Win32_EXE -type f -name '*.json' -exec grep --files-with-match -i 'dbtool' '{}';

Windows 版本: FIND /i "dbtool" \Win32_EXE*.json

问题:windows 语法缺少一个选项让我指定我想要在第一次匹配时返回结果。

这将搜索 *.json 文件并在其中搜索字符串dbtool 将 PUSHD 目录更改为您的搜索目录。

PUSHD "C:\src\t"
FOR /F "delims=" %%A IN ('DIR /S /B /A:-D "*.json"') DO (
    FIND /I "dbtool" "%%~A"
)
POPD

在 python 中,我将使用递归 glob:

from glob import iglob

def search(file):
    with open(file) as fo:
        for line in fo:
            if "dbtool" in line.lower():
                return True
    return False

for file in iglob("Win32_EXE/**/*.json", recursive=True):
    if search(file):
        print(file)

但我认为一般来说我不会使用 Python - 其他解决方案可能更快/更好。 例如 Powershell

get-childitem -recurse *.json | where-object { select-string -quiet -pattern "dbtool" -path $_ }

或者,如果您可以安装ripgrep ,那效果很好。

rg -l -g "*.json" -i dbtool Win32_EXE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM