Skip to content

Instantly share code, notes, and snippets.

@rogeriopradoj
Forked from letroll/Readme.md
Last active May 22, 2025 08:11
Show Gist options
  • Save rogeriopradoj/e805f74acedcfa43db58e199d4857d7f to your computer and use it in GitHub Desktop.
Save rogeriopradoj/e805f74acedcfa43db58e199d4857d7f to your computer and use it in GitHub Desktop.
bash script to split vcard in multiple chunk

copy vcard_splitter.sh chmod +x vcard_splitter.sh ./vcard_splitter.sh yourFile.vcf insert the number of part you want and tada

#!/bin/bash
# Check if a file is provided as an argument
if [ $# -ne 1 ]; then
echo "Usage: $0 file.vcf"
exit 1
fi
vcf_file="$1"
# Check if the file exists
if [ ! -f "$vcf_file" ]; then
echo "Error: File $vcf_file not found."
exit 1
fi
# Count the number of contacts
total_contacts=$(grep -c "BEGIN:VCARD" "$vcf_file")
echo "Total number of contacts: $total_contacts"
# Ask for the number of parts to split into
read -p "Into how many parts do you want to split the file? " num_parts
# Validate the input number
if ! [[ "$num_parts" =~ ^[0-9]+$ ]] || [ "$num_parts" -le 0 ]; then
echo "Error: Please enter a valid number greater than zero."
exit 1
fi
# Calculate the number of contacts per file
contacts_per_file=$((total_contacts / num_parts))
remainder=$((total_contacts % num_parts))
echo "Each file will contain approximately $contacts_per_file contacts (+1 for the first $remainder files)."
# Initialize variables
output_prefix="contacts_part"
file_index=1
current_count=0
current_file="${output_prefix}_${file_index}.vcf"
# Create and clear the first file
echo "Creating $current_file..."
> "$current_file"
# Check if any output file already exists
for i in $(seq 1 "$num_parts"); do
out_file="${output_prefix}_${i}.vcf"
if [ -e "$out_file" ]; then
echo "Error: The file $out_file already exists. Remove or rename it before continuing."
exit 1
fi
done
# Read and distribute contacts into separate files
while IFS= read -r line || [[ -n "$line" ]]; do
clean_line=$(echo "$line" | tr -d '\r') # Remove hidden carriage return characters
if [[ "$clean_line" == "BEGIN:VCARD" ]]; then
# Check if we need to switch to the next file
if [[ "$current_count" -ge "$contacts_per_file" && "$file_index" -le "$((num_parts - remainder))" ]] ||
[[ "$current_count" -ge "$((contacts_per_file + 1))" && "$file_index" -gt "$((num_parts - remainder))" ]]; then
file_index=$((file_index + 1))
current_file="${output_prefix}_${file_index}.vcf"
echo "Creating $current_file..."
> "$current_file" # Create an empty file
current_count=0
fi
fi
# Append the line to the current file
echo "$line" >> "$current_file"
if [[ "$clean_line" == "END:VCARD" ]]; then
current_count=$((current_count + 1))
fi
done < "$vcf_file"
echo "Splitting completed!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment