Last active
August 29, 2015 14:18
-
-
Save magalhini/eba51a2bd748a72a1712 to your computer and use it in GitHub Desktop.
This file contains 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
#!/bin/bash | |
# This script intends to remove all unused images from the project. | |
# Use with caution and don't forget to back-up before using. | |
SRC=./source/images | |
# Create a `.tmp` folder | |
mkdir -p .tmp | |
# List all images from source folder in `./.tmp/img_list` (exclude SVG files) | |
find $SRC -name '*.gif' -o -name '*.jpg' -o -name '*.png' -o -name '*.jpeg' > ./.tmp/img_list | |
# List all images used in Markdown files in `./.tmp/used_img_list` | |
grep --include='*.md' -Ro '!\[[^]]*\]([^)]*)' . | sed 's/[^(]*(//' | grep '^/images/' | sed 's/)$//' | sed 's/^/.\/source/' > ./.tmp/used_img_list | |
# Sort lists as `.sorted` | |
sort ./.tmp/img_list > ./.tmp/img_list.sorted && sort ./.tmp/used_img_list > ./.tmp/used_img_list.sorted | |
# Compare them in `./.tmp/diff` only to keep unused images | |
comm -23 ./.tmp/img_list.sorted ./.tmp/used_img_list.sorted > ./.tmp/diff | |
# Remove all unused images from `images` folder | |
# Unfortunately cannot use `xargs rm < ./.tmp/diff` because of spaces in filenames | |
cat ./.tmp/diff | while read file; do rm "$file"; done | |
# Clean possible empty folders | |
find $SRC -type d -empty -exec rmdir {} \+ | |
# Clean work station | |
rm -rf ./.tmp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment