#!/usr/bin/env bash

# Name: pgrep
# Author: Serafeim Zanikolas
# Date: Sun, 22 Jul 2007 14:12:26 +0100
# Description: filters the standard input with a pipeline of greps
# Syntax: pgrep <pattern> [..]
#         eg, "command | pgrep mail client,agent -gtk" translates to
#             "command | grep -i mail | grep -i 'client<CR>agent' | grep -i -v gtk"
#         meaning match lines with occurrences of "mail", and "client"
#         or "agent", and without "gtk"

cmd=""
std_switches="-i "

# iterate over the supplied keywords to build the pipeline command
while [ ! -z $1 ]; do
    if [ ${1:0:1} == "-" ]; then # if it starts with "-" use -v
        keywords=`echo ${1:1} | tr ',' '\n'`
        switches="$std_switches -v"
    else
        keywords=`echo $1 | tr ',' '\n'`
        switches="$std_switches"
    fi
    if [ -n "$cmd" ]; then
        cmd="$cmd | grep $switches '$keywords'"
    else
        cmd="grep $switches '$keywords'"
    fi
    shift
done

eval "$cmd"
