How can I prepend lines to beginning of file
hello
I know how to append lines to the end of files with a >> characters. Is there a way to add lines to the begiining of a file. thanks |
sed -i '1 i\some text' /home/me/somefile.txt
|
Or perhaps
cat file_with_more_lines oldfile >newfile mv newfile oldfile |
Another variant of cat with echo
Code:
echo "Put your text here" | cat - file > newfile |
Thats a good one. I was originally going to do a "(echo "Put your text here"; cat file) > newfile"
Yours is much better. |
Quote:
|
Quote:
The only advantage is that the inode number stays the same, as does any permissions on the file. |
I prefer "post #4," but with the additional step of moving (renaming ...) the old-file to an alternate name before moving the new-file into its place.
The advantage of this strategy is that it can be restarted if something goes wrong along the way. You create a new version of the output first, without altering any of the inputs, nor the existing version of the output. Briefly, the two exist side-by-side. Then, after moving the old-version out of the way (without destroying it ...), you finish the job. But, up to a point, if you then say ":eek: !!", your foot doesn't have a hole in it. You can compare the before-and-after files to make sure you didn't screw-up, and you can gracefully recover if when you do. (You can even archive the old versions, indefinitely, for statistical or auditing purposes.) |
Yes.
Without the need to keep old versions, the rename becomes an atomic operation. Other accesses get either the old file, or the new - but never a mix. |
Quote:
You can use the "--copy" option to preserve the inode number and its hard links. |
oops. Sorry about that.
|
Obviously, any "real" implementation of this idea would have to properly deal with concurrency, e.g. through a combination of exclusive file-locking [i](which Unix/Linux might not have ...) and sentinel-files. You would need to somehow know that someone was not already accessing the data, and that no one attempts to do so while the file-state is inconsistent. This is your responsibility to take care of, by whatever means are appropriate to your use-case. (It might be that there is no pragmatic need to do anything special at all.)
|
Which is why using "mv newname oldnazme" works.
|
Quote:
|
Which makes it atomic. Either you get the old version, or you get the new one.
Not a mix of old+new. Directory operations are atomic. |
All times are GMT -5. The time now is 01:12 AM. |