Bash/Mgrep

From Attie's Wiki
Revision as of 11:52, 3 October 2012 by Attie (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is a useful tool that extends grep.

  • Expression input is at the front, allowing quick & easy editing
  • Recursively locates all files named (e.g: *.c)
  • Multiple filenames may be specified
  • Uses grep's extended regex mode
  • Output shows file and line number, and is highlighted
  • If the output flows over the screen, less allows you to review the results
  • If the output doesnt flow over the screen, less quits immediately
#!/bin/bash
 
if [ $# -lt 3 ]; then
  echo "usage:"
  echo "  $0 <expression> <directory> <filename> [filename..]"
  exit 1
fi
 
EXPRESSION="$1";    shift
DIRECTORY="$1";     shift
 
FILES="-name '$1'"; shift
while [ $# -ne 0 ]; do
  FILES="${FILES} -or -name '$1'"; shift
done
 
CMD="find \"${DIRECTORY}\" ${FILES}"
eval ${CMD} | \
while read -r f; do
  grep -nH --color=always -E "${EXPRESSION}" "${f}"
done | \
less -FKnRX
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox