uiii
9/9/2013 - 7:00 PM

Search out all files in the current directory and subdirectories containing the given text and prints the lines with highlighted occurrences

Search out all files in the current directory and subdirectories containing the given text and prints the lines with highlighted occurrences.

#!/bin/bash

function processFile {
    if [[ "$1" == *-i* ]]
    then
        sedOptions='I' # case-insensitive
    fi

    grep -IHEn $1 "$2" $3 | sed -e "s/\($2\)/\x1b[0;33m\1\x1b[0m/${sedOptions}g" | cut -c -500
}

export -f processFile

if [ $# -lt 1 ]
then
  echo "usage: searchfile [<grep-options> ...] <search-string>"
else
    options=""
    while [ $# -gt 1 ]
    do
        options="$options $1"
        shift 1;
    done
    text="$1"
	find . -type f -exec bash -c "processFile \"$options\" \"$text\" \$0" {} \;
fi