65 lines
2.3 KiB
Bash
Executable File
65 lines
2.3 KiB
Bash
Executable File
#!/bin/bash
|
||
# This script recursively creates a table-of-contents file named !TOC.md in every directory
|
||
# under the current folder (e.g., your school folder). Each !TOC.md file will include:
|
||
# - A header with the directory name.
|
||
# - A list of immediate subdirectories (alphabetically sorted) as links to that subdirectory’s own !TOC.
|
||
# - A list of immediate files (alphabetically sorted) as links.
|
||
#
|
||
# IMPORTANT:
|
||
# - This script assumes that folder and file names do not include newline characters.
|
||
# - It uses bash arrays and assumes GNU coreutils are available.
|
||
|
||
# Set the base directory. Change "." if needed.
|
||
base_dir="."
|
||
find . -type f \( -iname "!TOC.md" -o -iname "README.md" \) -delete
|
||
|
||
# Recursively find every directory starting from base_dir.
|
||
find "$base_dir" -type d -print0 | while IFS= read -r -d '' dir; do
|
||
toc="$dir/!TOC.md"
|
||
|
||
# Write header into !TOC.md
|
||
echo "# Table of Contents for $(basename "$dir")" > "$toc"
|
||
echo "" >> "$toc"
|
||
|
||
#########################
|
||
# Process Subdirectories
|
||
#########################
|
||
subdirs=()
|
||
# Find immediate subdirectories (depth 1)
|
||
while IFS= read -r -d '' subdir; do
|
||
# Save only the basename of the subdirectory
|
||
subdirs+=( "$(basename "$subdir")" )
|
||
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d -print0)
|
||
|
||
if [ ${#subdirs[@]} -gt 0 ]; then
|
||
# Sort the subdirectory names alphabetically
|
||
sorted_subdirs=($(printf "%s\n" "${subdirs[@]}" | sort))
|
||
echo "## Subdirectories" >> "$toc"
|
||
for sub in "${sorted_subdirs[@]}"; do
|
||
# Link to the !TOC file inside the subdirectory
|
||
echo "- [[${sub}/!TOC]]" >> "$toc"
|
||
done
|
||
echo "" >> "$toc"
|
||
fi
|
||
|
||
#################
|
||
# Process Files
|
||
#################
|
||
files=()
|
||
# Find immediate files (depth 1), excluding the !TOC.md file itself.
|
||
while IFS= read -r -d '' file; do
|
||
files+=( "$(basename "$file")" )
|
||
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type f ! -iname "!TOC.md" -print0)
|
||
|
||
if [ ${#files[@]} -gt 0 ]; then
|
||
# Sort the file names alphabetically
|
||
sorted_files=($(printf "%s\n" "${files[@]}" | sort))
|
||
echo "## Files" >> "$toc"
|
||
for f in "${sorted_files[@]}"; do
|
||
echo "- [[${f}]]" >> "$toc"
|
||
done
|
||
echo "" >> "$toc"
|
||
fi
|
||
done
|
||
|