Why do you do this, fraq?
Occasionally I'll encounter myself doing something in Linux I don't do very often and I know other people aren't doing much as well. When that happens, I try to document the stupid, quirky things I did. Maybe for posterity, maybe because I need a life, I dunno.
What is the stupid trick today?
Every once in a blue moon, I have to inject a line at the top of a file. Sometimes it's an
import statement in python, sometimes it's a shebang line. While it's easy to just
vim ./filename and add it that way, it's more fun to try to do it programmatically. I've seen a few solutions using
sed, but I'd like to introduce a less popular tool:
tac reads files, but from bottom to top, moving the opposite direction of its cousin,
cat. You might have even noticed that
tac is just
cat backwards. Clever, eh?
tac doesn't get much attention, but this is one instance in which its actually useful.
Let's imagine you want to add an import statement at the top of a python script because you forgot it.
This won't work without
import os at the top, so let's add it.
tac useless_script.py > useless_script.tmp; echo "import os" >> useless_script.tmp && tac useless_script.tmp > useless_script.py && rm -f useless_script.tmp
Now, would it have been easier to use
sed? Almost certainly. Is this fun? I think so. Will you find a use for this? Yes, when you least expect it.