6
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 3 years have passed since last update.

PowerShell CSVの特定の列でフィルターして抽出/分割する

Last updated at Posted at 2021-03-07

読み込むCSVファイルの例として以下の input.csv を想定します。

category name
a sato
a suzuki
b takahashi

フィルターして一致する行のみ取り出す

categorya の行だけ抽出してCSVファイルを作ります。

Import-Csv input.csv | Where-Object { $_.category -eq 'a' } | Export-Csv output.csv -NoTypeInformation

出力は以下のようになります。

category name
a sato
a suzuki

なお、Export-Csv ではすべての値がダブルクォートで囲われて出力されるようです。

ダブルクォートを外すオプションは今の所ないようなので、外したい場合は下記のコマンドなどでダブルクォートを取りましょう……

Get-Content output.csv | ForEach-Object { $_.Replace('"','') >> output2.csv }

あるいは、文字列として読み込んでコンマでsplitする方法もあります。これならダブルクォートは付きません

Get-Content input.csv | Select-Object -First 1 > output.csv
Get-Content input.csv | Where-Object { $_.Split(',')[0] -eq 'a' } >> output.csv

フィルターしてファイルを分割する

category ごとに分割してCSVファイルを作ります。各行を <category>.csv というファイルに追記することで実現します。

Import-Csv input.csv | ForEach-Object { Export-Csv ($_.category + '.csv') -InputObject $_ -NoTypeInformation -Append }

なお、この方法も値にダブルクォートが付くので、外したい場合は別途消すか、下記のようなコマンドを使いましょう。

Get-Content input.csv | Select-Object -Skip 1 | ForEach-Object { $_ >> ($_.Split(',')[0] + '.csv') }

ちなみに ($_.category + '.csv')"$($_.category).csv" でもよいです。

あとがき

あまり詳しくないまま調べて書いたので、ベターな方法でなかったらすみません。

6
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
6
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?