Skip to content

Instantly share code, notes, and snippets.

@hamoid
Last active August 29, 2015 14:08
Show Gist options
  • Save hamoid/09cc65cd229626298741 to your computer and use it in GitHub Desktop.
Save hamoid/09cc65cd229626298741 to your computer and use it in GitHub Desktop.
Keep Markdown in sync when images are renamed
#!/bin/bash
# This scripts automatically updates text files when asset files are renamed
# Given page.md containing ![Image](/static/images/1234.jpg)
# if you rename the file 1234.jpg to awesome_jungle.jpg
# it will update page.md to ![Image](/static/images/awesome_jungle.jpg)
# Works on Linux (untested in Mac, where sed is slightly different).
# I place the script in my images/ folder and let it run while I rename images.
# DO NOT MOVE IMAGES IN or OUT OF THE FOLDER WHILE IT RUNS!
# IT WILL MESS THINGS UP! (because it expects moved_from +
# moved_to events in pairs, which happen only when renaming)
# Use git if you need undo.
# Possible improvements:
# Specify arguments for watch folder, markdown folder
# Make it recursive
# Make it resistant to files moved in/out of the folder: keep time stamp
# of events and only react if two events happen close in time.
# Ideally one could access the cookie with links events, is the cookie available?
# Don't expect moved_from first, then moved_to. (maybe it can be to > from?)
SCAN=/home/blog/content/post/*.md
COUNTER=0;
inotifywait -m --format '%f' -e moved_from,moved_to ./ | while read FILE
do
if [ $COUNTER -eq 0 ]; then
FROM="\/$FILE)";
COUNTER=1;
else
TO="\/$FILE)";
COUNTER=0;
grep -ilr "$FROM" $SCAN | xargs -d "\n" -I % sh -c 'echo "\nImage renamed\nUpdate % "; sed -i "/'$FROM'/{s/'$FROM'/'$TO'/g; w /dev/stdout
}" %;'
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment