Split (large) files in half using bash script

Alec Jacobson

June 21, 2010

weblog/

Here's a simple bash script that splits a given file into two equal (up to a byte) halves. It uses split which has different syntax between the GNU and BSD implementations, so see the comments for switching between the two. I tested this on a 6.4 GB dmg file and I was able to reverse the split with cat just fine. I diffed the re-concatenated file and the original and they were byte-wise equal. Save this in a file called half.sh:
#!/bin/bash
#
# usage: half foo 
#
# This will create foo.aa and foo.ab, where foo.aa is the first half(+1) of foo
# and foo.ab is the second half. Split by bytes not lines.
#
#
# To reverse just issue:
# cat foo.aa foo.ab > foo
#

# get file size
# GNU:
#size=`stat -c "%s" "$1"`
# BSD:
size=`stat -f "%z" "$1"`

# divide by 2 and round up
half_size=`echo "($size+1)/2" | bc`
split -b $half_size "$1" "$1."