iso27diy-corp/Corpus/Standards/ISO-27001-OST/ISO27001-NL-2023/rename-iso-title.zsh

90 lines
No EOL
1.9 KiB
Bash
Executable file

#!/usr/bin/env zsh
set -euo pipefail
execute=false
if [[ ${1:-} == '--execute' ]]; then
execute=true
shift
fi
if [[ $# -gt 0 ]]; then
print -u2 'Usage: rename-iso-title.zsh [--execute]'
exit 2
fi
# Requires Obsidian app running and CLI enabled.
: ${OBSIDIAN_CLI:=obsidian}
files=(c-[0-9]*\.md(N))
if (( ${#files} == 0 )); then
print 'No matching files found.'
exit 0
fi
for src in "$files[@]"; do
base=${src:t}
# Read the level 1 header from the file
# Format: # <number> <title>
# Extract everything after the first number and space
header=$(head -n 1 "$src" | sed 's/^# [0-9.]* //')
if [[ -z "$header" ]]; then
print -u2 "WARN skipped (no header found): $src"
continue
fi
# Clean up the title
title=$header
# Replace spaces with dashes
title=${title// /-}
# Remove commas, slashes, parentheses, quotes
title=${title//,/}
title=${title//\//}
title=${title//\\/}
title=${title//\(}
title=${title//\)}
title=${title//\'}
title=${title//\'}
# Replace diacritics with base characters
title=${title//ï/i}
title=${title//é/e}
title=${title//è/e}
title=${title//ê/e}
title=${title//ë/e}
title=${title//ö/o}
title=${title//ü/u}
title=${title//ó/o}
title=${title//ô/o}
title=${title//á/a}
title=${title//à/a}
title=${title//ã/a}
title=${title//ä/a}
title=${title//í/i}
title=${title//ì/i}
title=${title//ñ/n}
title=${title//ú/u}
title=${title//ù/u}
# Remove multiple dashes
title=${title//---/-}
title=${title//--/-}
# Remove leading/trailing dashes
title=${title#-}
title=${title%-}
# Build new filename: c-n.n-TITLE.md
ext="${src:r}.md" # extension without the extra .md issue
filename="${src%.*}"
target="${filename}-${title}.md"
if [[ $src == $target ]]; then
print "SKIP $src"
continue
fi
print "SRC $src"
print "DEST $target"
if $execute; then
"$OBSIDIAN_CLI" rename file="$src" name="$target"
fi
done