2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ディレクトリ内のテキストファイルで特定の文言を含むファイルを抽出するコマンド(Windows PowerShell)

Last updated at Posted at 2023-03-14

概要

特に外向けに難しいことを発信しようとしたわけでもなく、今後もたまに使いそうだと思った、ファイルの一括削除@Windowsローカル環境のコマンドレットを備忘しておきます、その2。

指定ディレクトリ内で、特定の文言を含むテキストファイルを抽出する

ファイルパスを出す

こういう感じ。

Get-ChildItem -Path "(ディレクトリパス)" -Filter *.txt -Recurse | ForEach-Object {
    if (Select-String -Path $_.FullName -Pattern "(検索したい文字列)") {
        Write-Output $_.FullName
    }
}

ファイルパスだけでなく、該当行の記述も出す

こういう感じ。

Get-ChildItem -Path "(ディレクトリパス)" -Filter *.txt -Recurse | ForEach-Object {
    $matches = Select-String -Path $_.FullName -Pattern "(検索したい文字列)"
    if ($matches) {
        Write-Output "File: $($_.FullName)"
        $matches | ForEach-Object {
            Write-Output "Line: $($_.LineNumber): $($_.Line)"
        }
    }
}

複数の文字列でも検索できるようにする

こういう感じ

$searchStrings = '文字列1', '文字列2', '文字列3', '文字列4', '文字列5'

Get-ChildItem 'C:\target_directory\*.txt' -Recurse | ForEach-Object {
    $filePath = $_.FullName
    $content = Get-Content $filePath

    foreach($searchString in $searchStrings) {
        $lineNumber = 0

        foreach($line in $content) {
            $lineNumber++
            if($line -match $searchString) {
                Write-Host "File: $filePath"
                Write-Host "Line #${lineNumber}: $line"
            }
        }
    }
}

終わり

大量のログファイルの中から、指定の文言があるかを調べるときに便利デスネ。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?