LoginSignup
0
1

More than 1 year has passed since last update.

PowerShellでテキストを処理する

Posted at

Powershellでテキスト処理

いまいちPowerShellにこなれていない感もあるがとりあえず。

PowerShellでテキストを処理するためのひな型

$file = $args[0]

# input SJIS is ok (default)
# use -Encoding UTF8 if file in UTF8

$i=1
foreach ($l in Get-Content -Encoding UTF8 $file) {
    #行を選択する
    if( $l -match "ガーシー") {
        #行を処理する
        $l = $l -replace "ガーシー", "■■"
        $l = $l -replace "、", "▼"
        $l += "↓"
        Write-Output $l
    }
    $i++
}

注意点

  • foreachの各行は行末の改行が取り除かれて渡される
  • -match は大文字小文字を区別しない。大文字小文字を区別するときは -cmatch をつかう
  • -replace は大文字小文字を区別しない。大文字小文字を区別するときは -creplace を使う
  • -replace を左辺で使うと対象を変更する。また標準出力に出力する。右辺で使うと対象を変更しない。また標準出力に出力しない。
  • -replace は置換対象を全て置換する。
  • -replace のバリアントとして-creplace, -ireplaceがある。 -creplaceはケースセンシティブ、-ireplaceはイグノアケースである
  • Get-Content のデフォルトはSJIS、UTF8のファイルを処理するときは明示的に -Encoding UTF8 を指定する。
  • Write-Output は必ず最後に改行する。出力の文字コードはUTF16
0
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
0
1