Skip to content

Instantly share code, notes, and snippets.

@pv8
Created July 24, 2015 18:03
Show Gist options
  • Save pv8/98f428ddd81a1c230794 to your computer and use it in GitHub Desktop.
Save pv8/98f428ddd81a1c230794 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Join multiple files
print_usage(){
echo "== joinfiles v0.1alpha =="
echo "joinfiles joins multiple files in a single one."
echo ""
echo "Usage:"
echo -e "\t./$(basename "$0") OUTPUT-FILE FILE1 FILE2 FILEn"
echo "or:"
echo -e "\t./$(basename "$0") OUTPUT-FILE FILE*"
}
# at least 2 arguments
if [[ $# -le 1 ]]; then
print_usage
exit 1
fi
function add_file() {
num_of_lines=$(($(wc -l < "$1") - 1))
total_lines=$(($total_lines + $num_of_lines))
echo "Adding $1 ($num_of_lines lines)"
tail -n +2 $1 >> $OUTPUT_FILE
}
PARAMS=($@)
FILE_LIST=("${PARAMS[@]:1}")
OUTPUT_FILE=${PARAMS[0]}
echo "Creating file: $OUTPUT_FILE"
for idx in "${!FILE_LIST[@]}"; do
if [[ "$idx" -eq "0" ]]; then
# insert header based on first file's header
head -1 ${FILE_LIST[idx]} > $OUTPUT_FILE
fi
add_file ${FILE_LIST[idx]}
done
echo "Checking $OUTPUT_FILE..."
num_of_lines=$(($(wc -l < "$OUTPUT_FILE") - 1))
if [[ $num_of_lines == $total_lines ]]; then
echo "OK! $num_of_lines lines read. $total_lines lines written."
else
echo "Ooops! Check file: $num_of_lines lines read. $total_lines lines written."
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment