Automate edit file with unix

24年 10月 9日 Wednesday
164 words
1 minutes

What's happening?

I migrate to disqus from waline and need to perform automation to add uuid automatically to each file in specified directory.

The problem

Things went wrong, and I didn't immediately recognize the issue. I failed to notice that the UUID wasn't unique, which caused the comment to persist across multiple pages.

bash
find src/content/posts/ -maxdepth 1 -type f -exec sed -i "0,/---/{/---/a\\
id: '$(node -pe "require('uuid').v4()")'
}" {} \;

The solution

To avoid bash expansion and force find command to re-exec node, I need to put the sed into a bash script file

bash
#!/usr/bin/sh

sed -i "0,/---/{/---/a\\
id: '$(node -pe "require('uuid').v4()")'
}" $1

chmod it and pass it to -exec

The conclusion

Fortunately, thanks to clean commit (each commit do one things), I can revert without facing merge conflict or losing other not-related changes.

text
git revert --no-commit <commit-id>

more explanation on stackoverflow.

Bonus

by the way, someone on IRC tell me: if your main operating system is linux, you can use uuidgen command instead of node, or just read it directly from /proc/sys/kernel/random/uuid, very neat huh? :)

Title:Automate edit file with unix

Author:ReYuki

Link:https://www.reyuki.site/posts/automate-edit-file-with-unix [copy]

Last updated:


This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. You are free to share and adapt it, as long as you give appropriate credit, don’t use it for commercial purposes, and distribute your contributions under the same license. Provided under license CC BY-NC-SA 4.0