Notionをエクスポートしたことがある人ならわかる、エクスポート後に末尾につくIDのような長い文字列が
邪魔だったので自動で消せるようにしました。
何度かエクスポートしないといけない事情がある人向け。
サブディレクトリは第2階層まで対応していてそれ以降は対応していないです。
# 置換対象の文字列を保存する配列
$foundSubstrings = @()
# 現在のディレクトリを取得
$rootPath = Get-Location
# ① ルートディレクトリのフォルダ名を変更
$directories = Get-ChildItem -Path $rootPath -Directory | Where-Object { $_.Name -notlike "bk*" }
foreach ($dir in $directories) {
$folderName = $dir.Name
# ② サブディレクトリのフォルダ名とHTMLファイル名を変更
$subDirectories = Get-ChildItem -Path $dir.FullName -Directory
$htmlFiles = Get-ChildItem -Path $dir.FullName -File -Filter "*.html"
foreach ($subDir in $subDirectories) {
$subFolderName = $subDir.Name
$subMatch = [regex]::Match($subFolderName, ' ([^ ]+)$')
if ($subMatch.Success) {
$subSubstring = $subMatch.Groups[1].Value
$foundSubstrings += $subSubstring
$newSubFolderName = $subFolderName -replace [regex]::Escape(" " + $subSubstring), ""
Rename-Item -Path $subDir.FullName -NewName (Join-Path $dir.FullName $newSubFolderName)
}
}
foreach ($htmlFile in $htmlFiles) {
$htmlFileName = $htmlFile.Name
$htmlMatch = [regex]::Match($htmlFileName, ' ([^ ]+)(?=\.html$)')
if ($htmlMatch.Success) {
$htmlSubstring = $htmlMatch.Groups[1].Value
$foundSubstrings += $htmlSubstring
$newHtmlFileName = $htmlFileName -replace [regex]::Escape(" " + $htmlSubstring), ""
Rename-Item -Path $htmlFile.FullName -NewName (Join-Path $dir.FullName $newHtmlFileName)
#htmlの中身を修正
$content = Get-Content (Join-Path $dir.FullName $newHtmlFileName) -Raw -Encoding UTF8
foreach ($substring in $foundSubstrings) {
$replacePattern = "%20$substring"
$content = $content -replace [regex]::Escape($replacePattern), ""
}
Set-Content -Path (Join-Path $dir.FullName $newHtmlFileName) -Value $content -Encoding UTF8
}
}
$match = [regex]::Match($folderName, ' ([^ ]+)$')
if ($match.Success) {
$substring = $match.Groups[1].Value
$foundSubstrings += $substring
$newFolderName = $folderName -replace [regex]::Escape(" " + $substring), ""
Rename-Item -Path $dir.FullName -NewName (Join-Path $rootPath $newFolderName)
}
}
# ③ ルートディレクトリのHTMLファイルの内容を変更
$htmlFiles = Get-ChildItem -Path $rootPath -File -Filter "*.html"
foreach ($htmlFile in $htmlFiles) {
$content = Get-Content $htmlFile.FullName -Raw -Encoding UTF8
foreach ($substring in $foundSubstrings) {
$replacePattern = "%20$substring"
$content = $content -replace [regex]::Escape($replacePattern), ""
}
Set-Content -Path $htmlFile.FullName -Value $content -Encoding UTF8
# ④ ファイル名を変更
$htmlFileName = $htmlFile.Name
$htmlFileMatch = [regex]::Match($htmlFileName, ' ([^ ]+)(?=\.html$)')
if ($htmlFileMatch.Success) {
$htmlFileSubstring = $htmlFileMatch.Groups[1].Value
$newHtmlFileName = $htmlFileName -replace [regex]::Escape(" " + $htmlFileSubstring), ""
Rename-Item -Path $htmlFile.FullName -NewName (Join-Path $rootPath $newHtmlFileName)
}
}