Skip to content

Instantly share code, notes, and snippets.

@yyano
Created March 19, 2019 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyano/b08e63730bf9b1e3c6affd3810fabf74 to your computer and use it in GitHub Desktop.
Save yyano/b08e63730bf9b1e3c6affd3810fabf74 to your computer and use it in GitHub Desktop.
日本語が混じる固定長のShift_JISファイルの特定位置の文字を編集(削る)するPowershell
# 固定長のShift_JISファイルの特定位置の文字を削除する
$filename = "hogehoge.txt"
$tempfile = "ZZZZZ_$filename"
$enc = [Text.Encoding]::GetEncoding("Shift_JIS")
$fhIn = New-Object System.IO.StreamReader($filename, $enc)
$fhOut = New-Object System.IO.StreamWriter($tempfile, $false, $enc)
$isCuted = $FALSE
# 1行ずつ処理
while (($l = $fhIn.ReadLine()) -ne $null) {
# 1文字ずつ処理
$tmpString = [System.Linq.Enumerable]::ToArray($l)
if($enc.GetByteCount($l) -le 760) {
Write-Host "すでに加工済みです"
$isCuted = $TRUE
break
}
$iCount = 0
$sOutLine = ""
foreach($tmpChar in $tmpString) {
$iCount = $iCount + $enc.GetByteCount($tmpChar)
# 特定位置の文字を処理しない
switch($iCount) {
{$_ -le 550} {$sOutLine = $sOutLine + $tmpChar} # <= 549
{$_ -ge 552 -band $_ -le 744} {$sOutLine = $sOutLine + $tmpChar} # >= 552 AND <= 744
}
}
$fhOut.WriteLine($sOutLine)
}
$fhIn.Close()
$fhOut.Close()
# ファイル名の変更
if($isCuted -eq $TRUE) {
Remove-Item $tempfile
} else {
$nowDate = Get-Date -Format "yyyyMMdd_HHmmss"
Move-Item $filename "$nowDate-$filename"
Move-Item $tempfile $filename
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment