×

Pages

Labels

Search

×

Pages

×
×

Notice

The site is currently undergoing scheduled maintenance, and may not function correctly. Please come back later.

Advertisement

advertisement

Memory Friendly Way Of Prepending Data To A File In Bash

While you can't prepend data to a file you can create a new file containing the data, and then append the original file data to it. To do this in a memory friendly way you'll need to copy the original file contents a little bit at a time. The DD command can be used to do this.

Steps:
Type, "echo -n 'data_to_prepend' > new_file | dd if='original_file' of='new_file' bs=1 seek=$(wc -c <new_file) && rm original_file". Replace "data_to_prepend" with the data you want at the start of the file. Replace "new_file" with a path to save the new file. Replace "original_file" with the path of the existing file.

Notes:
- DD's seek option uses a block size that is the same as the obs. By setting bs to '1' the obs is '1'. This matters because you need the seek size to be the same number of blocks that the WC -c command says the file size is in bytes.
- This example makes use of Bash, dd, rm, and wc.
- Tested on Lubuntu 18.04.

License:Comprehensible Open License 3.0

Comprehensible Open License 3.0

Material provided under the terms of this license can be used in any manner, provided the following conditions are met: The authors of the material are not held responsible for any consequence of using the material. The material remains under the terms of this license. The terms of this license are upheld in accordance with the federal laws of Canada in place as of January 1, 2019.

Advertisment

advertisement
Copyright © James Daniel Marrs Ritchey.

Siteviews