0

I want to split an image.jpg into parts and merge it again. I used the following commands:

split -b 1440 image.jpg # It divides it into 6 parts.
cat xaa.jpg xab.jpg xac.jpg xad.jpg xae.jpg xaf.jpg > new-image.jpg 

Now I want a script that does the same work of the previous commands.

dessert
  • 39,982
thmk
  • 1

1 Answers1

1

How about this:

#!/bin/bash

# test whether first argument exists and is a regular file, if not exit
[ -f "$1" ] || exit 1

# put 1440 bytes per output file
split -b 1440 "$1" "$1". &&

# merge files again
cat "$1".* >"${1%/*}/new-${1##*/}"

A script begins with a shebang specifying the program it should be run with, in this case that’s /bin/bash. First we test for the first argument to the script to be a regular file and exit if it’s not. The split command splits the file given as the first argument and creates output files like image.jpg.aa for a file image.jpg. Only if split exited successfully, the cat command merges them again using bash’s Pathname Expansion and Parameter Expansion and saves the output (i.e. the merged file) as new-image.jpg for a file image.jpg.

Save this script as e.g. splitmerge.bash, make it executable with chmod +x splitmerge.bash and run it with:

splitmerge.bash image.jpg

All output files are created in the input file’s directory regardless your current directory. If the script and/or the file to split is not located in your current directory, use absolute paths instead, e.g.:

~/scripts/splitmerge.bash /home/thmk/test/image.jpg
dessert
  • 39,982