LoginSignup
1
0

PowerShellでCSVの内容が重複していないか調べる

Last updated at Posted at 2024-01-13

ファイル名が異なるが中身が完全に重複しているかもしれないファイル群があり、重複の有無をチェックすることなったので……
※レコード毎の比較であり並び順は考慮しない

workフォルダ内イメージ

work\
    test.csv
    test2.csv
    test3.csv
    

作業フォルダ設定

#比較するCSVらがあるフォルダ
$work_path = "C:\Users\work"

Set-Location -Path $work_path

#作業フォルダ内で拡張子が.csvのみのファイルをフィルターして取得
$compare_files = Get-ChildItem -File -Filter *.csv

Compare-Objectでファイルの中身を比較できるみたいなので1 ループ処理で比較する

$same_file = @() #csvの中身が重複しているファイル名を格納する
$end_check = @() #$refで比較済のファイルが$defでも比較されると作業量が2倍になるので、比較済のファイル名を格納する

$compare_files | % {
    
    $ref = $null
    $ref = $_
    $ref_size = $ref.Length


    $compare_files | % {
        $def = $_
        $def_size = $def.Length
        if(($def.Name -notin $end_check) -and ($ref_size -eq $def_size)){ #$refで比較済のファイルが$defである場合とサイズが異なる場合は比較をスキップ
                 #比較した結果($result)がnullであれば重複しているので$same_fileにファイル名を格納する
            $result = Compare-Object (Get-Content (join-path $work_path $ref.Name)) (Get-Content (join-path $work_path $def.Name))

            if(($null -eq $result) -and ($ref.Name -ne $def.Name)){$same_file += ($ref.Name + "_" + $def.Name) 
            }
        }
     }

        $end_check += $ref.Name
}

#重複しているファイル名らをテキストに出力
Set-Content -PassThru (Join-Path $work_path "same_file.txt") -Value $same_file

問題点

  • 各ファイルが数百行程度ならCompare-Objectはすぐ終わるが、数万行などになると遅い
  • レコードの並び順が一致しているか否かは判定してくれないので順序も比較したい場合は別に考慮する必要がある
  • そもそも重複するような管理をしなければいい
  1. https://learn.microsoft.com/ja-jp/powershell/module/microsoft.powershell.utility/compare-object?view=powershell-7.4

1
0
2

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
1
0