How to write file into another

I have an empty file (only zeroes are in it) of size 9,0KB and I need to write another file (with size 1,1KB) to it, but the first file must not lose its size or the rest of its contents. So if the whole file is 00000000000000... now, I need to write second file in it and leave the zeroes as they are. I have tried to use dd, but I haven’t succeed – file resizes.

dd if=out/one.img of=out/go.img

Does anybody know how can I do it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

To overwrite the start of the destination file without truncating it, give the notrunc conversion directive:

$ dd if=out/one.img of=out/go.img conv=notrunc

If you wanted the source file’s data appended to the destination, you can do that with the seek directive:

$ dd if=out/one.img of=out/go.img bs=1k seek=9

This tells dd that the block size is 1 kiB, so that the seek goes forward by 9 kiB before doing the write.

You can also combine the two forms. For example, to overwrite the second 1 kiB block in the file with a 1 kiB source:

$ dd if=out/one.img of=out/go.img bs=1k seek=9 conv=notrunc

That is, it skips the first 1 kiB of the output file, overwrites data it finds there with data from the input file, then closes the output without truncating it first.

Method 2

Just open the target file in read-write mode with the <> shell redirection operator instead of write-only with truncation with >:

Assuming you want to write file2 on top of file1:

cat file2 1<> file1

That would write file2 into file1 at offset 0 (at the beginning).

If you want to append file2 at the end of file1, use the >> operator.

cat file2 >> file1

You can also write file2 at any offset within file1 with:

{ head -c1000 # for 1000 bytes within or
  # head -n 10 # for 10 lines within
  cat file2 >&0
} <> file1 > /dev/null

Though for byte offsets, you’ll probably find using Warren’s dd solutions to be more convenient.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x