powershell

PowerShellで囲まれた文字列抽出

ログファイルや、htmlファイルから『×××で囲まれた部分を抽出したい』要件に遭遇しますがそんな時にはこのスクリプトをベースに回収して適宜使っています。

<# カッコ『()』で囲まれた時  ※\でエスケープしてます#>
$regex = '\(.+?\)'

<# ダブルクォーテーション『""』 で囲まれた時#>
$regex = '".+?"'

<# htmlタグ等(例として)『<t     </td>"』 で囲まれた時#>
$regex = '<td.+?</td>'
# 元のファイルパス
$sourceFile = 'D:\temp\test2.txt'
# 出力ファイルパス
$newFile = 'D:\temp\test3.txt'
# 対象なしの行を出力ファイルへ出力するか否か
$empty_line_out = 0  # 1:出力しない  0:出力する
#セパレータ
$separator="`t"
# 正規表現パターン
#$regex = '\(.+?\)'
$regex = '".+?"'
#$regex = '<td.+?</td>'
if(Test-Path $newFile){Remove-Item $newFile}
$lno=1
foreach ($line in Get-Content  -Encoding "UTF8" $sourceFile) {
    $ret = [RegEx]::Matches($line, $regex)
    $lno++
    $ret |
    ForEach-Object -begin {
        $i=0
        $ou=""
    }  -Process { 
        if( $i -gt 0) 
        { 
            $ou=$ou +"`t"+$_.value; 
        } 
        else 
        {
            $ou=$ou + $_.value;
        }
        $i++; 
    } -end {
        if( $i -ge $empty_line_out ) 
        {
            $stlin = "{0:D10}" -f $lno
            Write-output  $stlin$separator$ou | Out-File $newFile -Encoding default -Append
        }
    }
} 
Get-Content $newFile
以下解説
Shift_JISでファイル出力する際は -Encoding default

ファイル出力には「Out-File」を使いますがShift_JISで出力する際は -Encoding defaultを使用します。

Out-File $newFile -Encoding default    #Shift_JIS
Out-File $newFile -Encoding String     #utf-16 BOM付
Out-File $newFile -Encoding utf8       #utf-8 BOM付

スポンサーリンク
タイトルとURLをコピーしました