How do I append a specific number of null bytes to a file? [closed]

I have a script that writes to a few files but I need them a specific size. So I'm wondering if there's a way of appending a specific number of null bytes to a file by using standard command line tools (e.g, by copying from /dev/zero)?


Solution 1:

truncate is much faster than dd. To grow the file with 10 bytes use:

 truncate -s +10 file.txt 

Solution 2:

You can try this as well

dd if=/dev/zero bs=1 count=NUMBER >> yourfile

This will read from /dev/zero and append to yourfile NUMBER bytes.

Solution 3:

Below is an example of appending 10MB to a file using only dd.

[root@rhel ~]# cp /etc/motd ./test
[root@rhel ~]# hexdump -C test |tail -5
000003e0  0a 0a 3d 3d 3d 3d 3e 20  54 65 78 74 20 6f 66 20  |..====> Text of |
000003f0  74 68 69 73 20 6d 65 73  73 61 67 65 20 69 73 20  |this message is |
00000400  69 6e 20 2f 65 74 63 2f  6d 6f 74 64 20 3c 3d 3d  |in /etc/motd <==|
00000410  3d 3d 0a                                          |==.|
00000413

[root@rhel ~]# dd if=/dev/zero of=/root/test ibs=1M count=10 obs=1M oflag=append conv=notrunc
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.0208541 s, 503 MB/s

[root@rhel ~]# hexdump -C test |tail -5
00000410  3d 3d 0a 00 00 00 00 00  00 00 00 00 00 00 00 00  |==..............|
00000420  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00a00410  00 00 00                                          |...|
00a00413

Solution 4:

my first guess would be:

dd if=/dev/zero of=myfile bs=1 count=nb_of_bytes seek=$(stat -c%s myfile)

Basically, this command tells dd to "go" at the end of the file and add some bytes previously read from /dev/zero.

Regards,