0

I'm trying to create two separate options to search through a file, one for phone numbers and one for emails. Nothing seems to happen when I run the file at the moment.

#!/bin/sh
while getopts ":-e:-p:" option; do
case $option in

-e)   egrep -o  "\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+.[a-zA-Z0-9.-]+\b" $2 ;;


-p)   egrep -o "^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$" $2 ;;


esac

done
Cyrus
  • 84,225
  • 14
  • 89
  • 153

1 Answers1

1

Consider using variables to reduce duplication, and enforce that the two options are mutually exclusive (which I think is what your description says). I also escaped the period in your email regex with \.:

#!/bin/sh

while getopts 'e:p:' option
do
    case "$option" in
        e)
            regex="\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b"
            file=$OPTARG
            ;;
        p)
            regex="^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$"
            file=$OPTARG
            ;;
    esac
done
if [ -z "$regex" ]
then
   # error handling
fi
egrep -o "$regex" "$file"

Use arguments instead of options if email or phone is required (sneaked in alternative long names for documentation):

#!/bin/sh

case "$1" in
  e|email)
    regex="\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b"
    ;;
  p|phone)
    regex="^((\([0-9]{3}\) )|([0-9]{3}\-))[0-9]{3}\-[0-9]{4}$"
    ;;
esac
if [ -z "$regex" ]
then
  echo e or p required
  exit 1
fi

if [ -z "$2" ]
then
  echo file required
  exit 1
fi
file=$2

egrep -o "$regex" "$file"

I reverse engineered your regex to generate the sample data that I asked you for earlier:

cat >input.txt
a bc@de.fg h
(123) 456-7890
123-456-7890
^D

and here is the result of running the 2nd script over the test data:

./Myfile.sh e input.txt
bc@de.fg
./Myfile.sh p input.txt
(123) 456-7890
123-456-7890

Btw, it's a good idea to leave out the .sh suffix. This allows you to seamless rewrite your program in another language should the need arise.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • So, the same thing that happens when I run my original script happens, which is nothing. When I try to run it through ./ I get ~/scripting]$ ./Myfile.sh e input.txt ~/scripting]$ Providing no output from the file – jimmy matics Sep 19 '21 at 13:11
  • In your question you did not show an example of the `input.txt`. When you don't have emails in the file, an empty output ws to be expected. How did you continue? Did you add `echo "going to grep"` or `set -x` for debugging your situation? – Walter A Sep 19 '21 at 16:03
  • @jimmymatics I fixed the email regex to escape the period `.`. and generated test data to demonstrate that script works as claimed. You are making it hard to help you without sample test data. Also fixed a few issues in the 2nd script so make sure you update it. – Allan Wind Sep 19 '21 at 19:44
  • (I thought \b was PCRE specific but seems to work as is) – Allan Wind Sep 19 '21 at 19:54