[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Prepending text to the beginning of a file
From: |
Akbarkhon Variskhanov |
Subject: |
Prepending text to the beginning of a file |
Date: |
Fri, 17 Jun 2022 01:48:43 +0500 |
Yes, there is sed and ed that can do just that.
But I was just wondering if it can be done with the shell's built-ins and
maybe `cat`.
We can concatenate files in the order they're given and output that to
another file. Working as intended!
But what if some data is stored in a variable and we want to prepend it to
the beginning of a file without creating temporary ones? Sort of like a >>
but before the buffer.
I tried something like
exec 3<>somefile
cat - <&3 >&3 <<eof
$(var)
eof
And it didn't truncate the file, but also overwrote the first couple of
lines. To be honest, I can't quite grasp the <> operator's purpose.
Then I stumbled upon this neat hack: https://stackoverflow.com/a/54715861
echo "$(echo -n 'hello'; cat filename)" > filename
But that only works if the file is small and fits into echo's arg list.
Please, share your ideas and thoughts. I'm very curious to read them. Try
not to resort to editors. :)
Thank you.
- Prepending text to the beginning of a file,
Akbarkhon Variskhanov <=