Helping with BASH scripting

Had a question in one of my tech communities about needing a BASH script to split a bunch of CSV files into two halves with appending a 1 or 2 to the filenames. Below is one way to do it that I wrote in a couple minutes. Watch for line-wrap in the next to last line.

#!/bin/bash
for i in *.csv; do
	csvlength=$(wc -l $i | cut -d' ' -f1)
	splitlength=$(( $csvlength - ($csvlength / 2)))
	split -l${splitlength} --numeric-suffixes=1 -a1 --additional-suffix=.csv $i $( echo $i | cut -d'.' -f1)
done

split -nl/2 could be used if either all lines are the same length or if uneven splits are acceptable because -n splits based on byte size.

The math with the splitlength variable is because of how math works in BASH; it’s integer and rounds down. If the file has an odd number of lines then dividing by two alone would result in a third file being created with a single line. This way the extra line is included in the first file.

There are several issues present, of course. It assumes all files are readable, and if any have a single line it gives an error, and it doesn’t deal with if there’s a header line. Hence, a quick script to get a small job done.