Last active
April 8, 2025 23:00
-
-
Save mminer/76acfab2dee8976cc12f40dfa38a9037 to your computer and use it in GitHub Desktop.
Bash script to remove leading indent from code snippets.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Read lines from stdin into array: | |
lines=() | |
while IFS= read -r line; do | |
lines+=("$line") | |
done | |
# Find minimum indentation level: | |
min_indent=0 | |
first_non_empty=true | |
for line in "${lines[@]}"; do | |
# Skip lines that are empty or only contain whitespace. | |
if [[ -z "$line" || "$line" =~ ^[[:space:]]*$ ]]; then | |
continue | |
fi | |
leading_whitespace=$(echo "$line" | sed -E 's/^([[:space:]]*).*$/\1/') | |
indent=${#leading_whitespace} | |
if [[ "$first_non_empty" = true || $indent -lt $min_indent ]]; then | |
min_indent=$indent | |
first_non_empty=false | |
# If there's no indentation, we're done. | |
if [[ $min_indent -eq 0 ]]; then | |
break | |
fi | |
fi | |
done | |
# Remove minimum indentation from all lines: | |
for line in "${lines[@]}"; do | |
if [[ -z "$line" ]]; then | |
echo "" | |
elif [[ "$line" =~ ^[[:space:]]*$ ]]; then | |
echo "$line" | |
else | |
echo "${line:$min_indent}" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment