CCCPaste

VCARD to CSV

#!/bin/bash
###################################################################### 
#Copyright (C) 2023  Kris Occhipinti
#https://filmsbykris.com

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation version 3 of the License.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see .
###################################################################### 

#converts VCARD file to a simple CSV with just Names and Numbers

tmp_dir="/tmp/contact_split"
vcard_dir="$HOME/Documents/$(date +%Y)/phone/sync"
vcard_file="${vcard_dir}/contacts.vcard"
csv_file="${vcard_dir}/contacts.csv"

mkdir -p "$tmp_dir"
cd "$tmp_dir" || exit 1

csplit -z "$vcard_file" /BEGIN:VCARD/ '{*}' > /dev/null

function create_csv(){
  f="$1"
  name="$(grep "^FN:" "$f"|sed 's/FN://g'|dos2unix)"
  numbers="$(grep "^TEL" "$f"| sed 's/[^0-9]*//g'|tr "\n" ","|dos2unix)"
  echo "${name},${numbers}"
} >> $csv_file

echo -n "Converting Vcard to CSV..."
for f in *
do
  echo -n "."
  grep -q "^TEL" "$f" && grep -q "^FN" "$f" && create_csv "$f"
done

#clean up
grep -v ",$" "$csv_file"|grep -v "^[0-9]"|sort -u| sponge "$csv_file"

echo
echo "$csv_file created."
rm -fr "$tmp_dir"