writing

mostly bash/gitbash-compliant ports of Python scripts to have some automations on restricted Windows machines

populate/replace Alt text for images in markdown files

requires a csv:

filename,alt_text
main-config.png,Screenshot of the main configuration screen
...

Basically a wrapper for sed (with -E to ensure proper handling of escapes in pattern)

Click to see code...
#!/bin/bash

# Check args
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <csv_file> <md_files_directory>"
    exit 1
fi

csv_file="$1"
md_dir="$2"

# Check if CSV file exists
if [ ! -f "$csv_file" ]; then
    echo "Error: '$csv_file' not found."
    exit 1
fi

# Check if directory exists
if [ ! -d "$md_dir" ]; then
    echo "Error: '$md_dir' not found."
    exit 1
fi

# Read CSV
while IFS=',' read -r image_name alt_text; do
    # Skip empty lines/fields
    if [[ -z "$image_name" || -z "$alt_text" ]]; then
        continue
    fi
    alt_text=$(echo "$alt_text" | tr -d '\r\n')
    echo Adding: $alt_text
    echo to: $image_name
    echo ""

    # Escape special chars in image_name (for grep/sed)
    image_name_escaped=$(echo "$image_name" | sed -e 's/[\\&/]/\\\\&/g')

    # Find-replace in all .md files in the directory 
    find "$md_dir" -type f -name "*.md" -exec sed -E -i \
        "s/!\\[[^]]*\\]\\(([^)]*\/$image_name_escaped[^)]*)\\)/![${alt_text}](\1)/g" {} +

done < <(tail -n +2 "$csv_file") # Skip the header

Last updated