目录
- $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)
- }
- }
- }
- 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))