powershell 搜索文本并返回行号

目录

powershell 搜索文本并返回行号 

python调用powershell搜索文本并返回行号;


powershell 搜索文本并返回行号 

$keyword = 'PS'
dir "d:\" -Filter "*.txt" -Recurse | foreach {
    $line = 0 
    $fileName = $_.FullName
    Get-Content $fileName | foreach {
        $line++
    
        if($_.Contains($keyword)){
       Write-Host ("(line:{0}) {1}" -f $line, $fileName)
        }
    }
} 

python调用powershell搜索文本并返回行号;

    file_path = r'2023-09-10.txt'

    search_string = ' 10575'

    dir_path, file_name = os.path.split(file_path)

    # 定义 PowerShell 命令
    cmd = f'''
    $keyword = '{search_string}'
    dir "{dir_path}" -Filter "{file_name}" -Recurse | foreach {{
        $line = 0 
        $fileName = $_.FullName
        Get-Content $fileName | foreach {{
            $line++
            if($_.Contains($keyword)){{
                "(line:$line) $fileName"
            }}
        }}
    }} 
    '''

    result = subprocess.run(['powershell', '-Command', cmd], capture_output=True, text=True)

    matches = re.findall(r'\(line:(\d+)\) (.+)', result.stdout)


    for match in matches:
        line_number, file_name = match
        print(int(line_number))

你可能感兴趣的:(win/ubuntu,服务器,前端,python)