#!/bin/bash # Bad Code Search, with syntax highlighting. # # Sample usage: # bcs.sh --file Lines.*cs Vector3 # bcs.sh -i new vector3 # https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash POSITIONAL=() while [[ $# -gt 0 ]] do key="$1" case $key in -f|--file) FILE="$2" shift # past argument shift # past value ;; -i|--ignore-case) GREP_FLAGS="-i" shift # past argument ;; *) # unknown option POSITIONAL+=("$1") # save it in an array for later shift # past argument ;; esac done set -- "${POSITIONAL[@]}" # restore positional parameters if [[ -z $@ ]]; then echo 'Usage: bcs.sh [-i] [-f/--file FILE_PATTERN] QUERY' exit 1 fi # highlight(1) sticks some ANSI cruft into the output. # We just turn spaces into "match anything", which kinda ignores the cruft. QUERY=`echo $@ | sed -e "s/ /.*/g"` if [[ -n $FILE ]]; then files=$(git ls-tree -r master --name-only | grep "$FILE") if [[ -z $files ]]; then echo "no files matched" exit 0 fi for file in `grep -l $GREP_FLAGS "$QUERY" $files`; do echo $file: highlight --force --line-numbers -O xterm256 --stdout $file | \ grep -C 5 $GREP_FLAGS "$QUERY" --label=$file | perl -pne s%^--\$%$file:% done else for file in `grep -l $GREP_FLAGS "$QUERY" $(git ls-tree -r master --name-only)` do echo $file: highlight --force --line-numbers -O xterm256 --stdout $file | \ grep -C 5 $GREP_FLAGS "$QUERY" --label=$file | perl -pne s%^--\$%$file:% done fi