PowerShell ISEに以下のコードを張り付けて、適宜編集してどうぞ。
# 入力ファイルのパス
$inputFile = "C:\path\to\input.txt"
# 出力フォルダ(存在しない場合は作成)
$outputDir = "C:\path\to\output"
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir | Out-Null
}
# 分割する行数
$linesPerFile = 1000
# カウンタとバッファ
$lineCount = 0
$fileCount = 1
$buffer = @()
# 入力ファイルの各行を処理
Get-Content $inputFile | ForEach-Object {
$buffer += $_
$lineCount++
if ($lineCount -eq $linesPerFile) {
$outFile = Join-Path $outputDir ("output_{0:D3}.txt" -f $fileCount)
$buffer | Set-Content $outFile
$fileCount++
$lineCount = 0
$buffer = @()
}
}
# 残った行があれば最後のファイルとして保存
if ($buffer.Count -gt 0) {
$outFile = Join-Path $outputDir ("output_{0:D3}.txt" -f $fileCount)
$buffer | Set-Content $outFile
}
●実行方法
上記のコードを Split-File.ps1 などの .ps1 ファイルに保存
PowerShell を開いて、スクリプトを実行:
.\Split-File.ps1
必要に応じて、出力ファイル名のフォーマットや文字エンコーディング(-Encoding UTF8 など)もカスタマイズ可能です。
PowerShell SEに張り付けても可能です。
環境により修正すべき変数
$inputFile:分割対象のファイル
$outputDir:分割ファイルの保存先ディレクトリ
$linesPerFile:1ファイルあたりの行数
分割対象ファイルのファイルがCSV形式で文字コードがEUCの場合
前記のコードですと停止するので文字コード指定する必要があります。Solarisから大量のテキストやCSVを渡された場合は下記を使用してください。
# 入力ファイルと出力フォルダ
$inputFile = "C:\path\to\input.csv"
$outputDir = "C:\path\to\split_csv"
$linesPerFile = 1000
# 出力フォルダを作成(存在しない場合は作成)
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir | Out-Null
}
# EUC-JP エンコードを取得
$encoding = [System.Text.Encoding]::GetEncoding(51932)
# 全行を EUC-JP で読み込み
$lines = [System.IO.File]::ReadAllLines($inputFile, $encoding)
# ヘッダー行(最初の1行)
$header = $lines[0]
$dataLines = $lines[1..($lines.Length - 1)]
# 分割処理
$fileCount = 1
for ($i = 0; $i -lt $dataLines.Count; $i += $linesPerFile) {
$chunk = $dataLines[$i..([Math]::Min($i + $linesPerFile - 1, $dataLines.Count - 1))]
$outPath = Join-Path $outputDir ("split_{0:D3}.csv" -f $fileCount)
# EUC-JPで書き出し(ヘッダー付き)
$writer = New-Object System.IO.StreamWriter($outPath, $false, $encoding)
$writer.WriteLine($header)
$chunk | ForEach-Object { $writer.WriteLine($_) }
$writer.Close()
$fileCount++
}
ご参考まで。