0

I have a text file containing US phone numbers. I am writing a shell script to convert them to E.164 format.

I think I just need to remove every character except numbers, and then add "+1" on the front. So if the phone number looks like (800) 123-4567 or 1-800-123-4567 e.g., it should be formatted as +18001234567.

How do I do this, with just shell scripting?

Similar Questions

Steve K
  • 2,044
  • 3
  • 24
  • 37
  • Is it one number per line? Do you have example input and output? Did you start on this and failed? How exactly? – Benjamin W. Mar 18 '19 at 13:44
  • Yes one number per line, e.g.: `(800) 123-4567` on the first line, `1-800-123-4567` on the second, etc. Trying to figure out if someone else has already done this. Currently attempting it with something like `e164=$(echo "+1$(echo "$phone_number" tr -dc '0-9')")` – Steve K Mar 18 '19 at 14:11

1 Answers1

1

just shell

#!/bin/sh

phonefile="numbers"
exec 0< "${phonefile}"
outfile="e164"
exec 1> "${outfile}"

IFS='()- '
while read number
do
 if [ -z "${number%%1*}" ] ; then
  printf "+"
 else
  printf "+1"
 fi
 printf "%s" ${number}
 printf "\n"
done

More general version:

#!/bin/sh

numberfilter() {
  local phonefile="$1"
  local outfile="$2"
  local filter="$3"
  local countrycode="$4"

  exec 3<&0
  exec 0< "${phonefile}"
  exec 4<&1
  exec 1> "${outfile}"

  local oldIFS="$IFS"
  IFS='()- '
  while read number
  do
  case ${number} in
      +*)             ;;
    011*)   number=${number#011} ; printf  '+'  ;;
     00*)   number=${number#00} ;  printf  '+'  ;;
      1*)   printf  '+'  ;;
       *)   printf  "+${countrycode}" ;;
  esac
  printf '%s' ${number}
  printf '\n'
  done

  IFS="${oldIFS}"
  exec 0<&3
  exec 3<&-
  exec 1<&4
  exec 4<&-
}

numberfilter numbers e164_1 '()- ' 1
numberfilter numbers e164_55 '()- ' 55
xenoson
  • 163
  • 3
  • Works great, thanks! I tested this with `1-800-555-1212`, `800-555-1212`, and `(800) 555-1212`, and it worked for all three! – Steve K Mar 19 '19 at 18:21