#!/bin/bash

# trap ctrl-c and call ctrl_c()
trap ctrl_c INT

ctrl_c() {
  echo
  echo 'Caught Ctrl-C. Exiting...'
  exit 1
}

ipv4cidrregex='(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))/(([0-8]{1})|([0-2][0-9])|(3[0-2]))'

grepfile() { grep -oE "${ipv4cidrregex}" "${@}"; }
grepit() { grep -oE "${ipv4cidrregex}"; }

# if arguments are passed:
if [ ! -z $1 ]; then
  for i in ${@}; do
    # if $i is a file:
    if [ -f "$i" ]; then
      grepfile "$i"
    else
      # if argument is input from stdin:
      echo "$i" | grepit
    fi
  done
else
  grepit
fi
