76

I need to copy the content of a folder which contains binary files to one binary file in another directory.

In Windows I can just use:

copy file1 + file2 targetfile /B 

I couldn't find something similar for Linux (I saw an approach with cat, but I'm unsure if this really works for binary files).

funky-future
  • 3,716
  • 1
  • 30
  • 43
Ahatius
  • 4,777
  • 11
  • 49
  • 79

2 Answers2

120

Unix has no distinction between text and binary files, which is why you can just cat them together:

cat file1 file2 > target_file

If target_file already exists and you want to append content to it, instead of overwriting, use instead:

cat file1 file2 >> target_file
ferdymercury
  • 698
  • 4
  • 15
geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • 3
    Unfortunately this messes up the binary data. I guess it is caused by some encoding issue? ASCII strings inside the binary data are ok in the resulting file but bytes outside the ASCII range are messed up (I guess they are replaced by UTF-8 replacements?). How can I tell cat to ignore encodings and just concat the files byte per byte? – Robert S. Jan 27 '21 at 13:51
  • 2
    From what I read everywhere cat should not care about encodings and just work with binary files. But it doesn't in my case. I use /bin/cat inside an appveyor Ubuntu environment. Maybe they use another cat? – Robert S. Jan 27 '21 at 14:00
  • 1
    Side note: if target_file exists in advance and you want to append content to it, rather than overwriting it, use the >> operator instead of >. – ferdymercury May 13 '22 at 17:21
  • @ferdymercury Please do consider editing the answer to include the `>>` part; it saved me today. Typically comments aren't read & thus would help someone as well :) – Bond - Java Bond Sep 07 '22 at 10:59
  • 1
    @Bond I edited as suggested but it's waiting approval – ferdymercury Sep 08 '22 at 11:08
36

cat is a very useful utility that will output the content of one or more files to standard output. That can be redirected with shell-funcionality into a file. It will work with binary or ascii files. In some programming languages that do not use linking, cat is used to merge binary files into a single executable file.

cat file1 file2 > target_file
choroba
  • 231,213
  • 25
  • 204
  • 289
  • how do you seperate them? :) without knowing the offset – Izzy Kiefer Jun 28 '23 at 01:30
  • @IzzyKiefer: The application must understand the format of the files and the file must contain some information about its size or end etc. Sometimes, it's not possible, but also not needed. – choroba Jun 28 '23 at 07:47