Front Matter Script

For a little while now I have been thinking it would be good to have a date modified on my posts and pages. Over the years I have updated quite a few of them, and some of my blog posts are more of a living post.

I just updated this page along with the script listing on here. I spent some time working on it today. The approach I had been thinking was the best way to verify that there isn’t a date-updated field was by making regex work for me. Regex is so powerful. I just don’t often have a use for it, so I get it gets a little stale in my brain.

I have run it on all my pages and it seems to work fine now. It didn’t the first run.

Always use a copy of your files or keep a backup when doing things en masse like this. Things can and will get broken.

In my initial testing it seems to work perfectly. Consider it a work in progress, though. But what isn’t? I just did a quick little test, and it seems to do exactly what I expect.

Now I have updated it to take both files and folders and do some basic verification instead of just blindly doing things. There is still work to do, but I have it, so it is not messing up the _index.md files now.

I have also updated the script to check whether the updated field matches what it should be. If not, it updates it. If they match, it moves on without overwriting the file.

#!/bin/sh
trap ctrl_c INT

ctrl_c () {
    echo "Exiting"
    exit 1
}

do_updated() {
set e 
PATTERN="^updated = [0-9]+-[0-9]+-[0-9]+[0-9T:]+"
N="
"
Tax="\[taxonomies\]"
Extra="\[extra\]"
t=$(stat -f %Sm -t  "%Y-%m-%dT%H:%M:%S"   $file )
updated=$(echo $N"updated = "$t$N)
basename=$(basename $file)

if [ "$basename" = "_index.md" ]; then
continue
 else
 if   grep -q "$t" $file ; then
echo "$t already exists in $f"
 else
 echo "updated to $f correct $t"
if  grep  -q -E "${PATTERN}"  $file  ; then
sed    -i '' -E  "/${PATTERN}/c \\
$updated" $file
 touch  -m  -d $t $file
else
if grep -q "${Tax}" $file; then
sed   -i ''   "/$Tax/i\\
$updated" $file
 touch  -m  -d $t $file
 else 
 sed   -i ''   "/$Extra/i\\
$updated" $file
 touch  -m  -d $t $file
fi

fi
fi
fi
}
for f in "$@"; do
	if [ -d "$f" ]; then
		files=$(find $f -type f -name "*.md")
		for filename in $files; do
            file=$filename
			do_updated
		done
	elif [ -f "$f" ]; then
		file="$f"
do_updated
	else
if  [ ! "-" == $(echo "$f" | cut -c -1) ]; then
		echo "$f is neither a file or directory"
		
	fi
	fi
done

My next step, I think, is to add some options to let it do some other things to manipulate fields and other stuff in the front matter. There have been times when I had to do that in the not too distant past. That could also be useful should I ever decide to switch static site generators. I don’t foresee that happening, as I love the changes that have been made in Zola and tera but you never know?

This works on FreeBSD and doesn’t use anything that is not in the base system.