Shell – Can we merge binary files without any copy operation by handling filesystem

filesfilesystemslinuxshell

I would like to merge efficiently binary files using a shell command and I quickly found classical ways like this one :

cat file1 file2 > file3

Not bad but :

  1. It's slow. IO access are slow.
  2. It needs extra space. I don't want to copy the files. Just concatenate them.

File systems are great to handle file fragmentation. Can't we just merge files using this mecanism?

Best Answer

You can do this:

cat file2 file3 [...] filen >> file1

This will concatenate file2, file3,..., filen to the end of file1 in-place. The >> operator tells the shell to write to the end of the file.

You want to leverage the file system to "handle file fragmentation". Unfortunately, there isn't any general way to do this. It's because "file systems" are much more general than file systems on disks — for example, you have NFS, FUSE, and many other mechanisms which let you expose any kind of resource (not just block devices such as hard disks) as a file system hierarchy. Even for block-device-based file systems, there isn't a standard mechanism to do this, and I don't know any implementation-specific ones either.

Related Question