Week of bash scripts – grok and cdf

Header

These two scripts are two different find commands. The first (grok) will list all files in a directory recursively that contain matched text, and the second will locate a file/folder and the change to it’s directory. Neither of these are mine (though slightly edited), I’ve gotten them from the Arch forums where they have a great thread called Post your handy self made command line utilities.

Grok

This one is by rebugger and I call it grok. Syntax is:

grok <keyword> <*location>

If no location is given it begins the search in the current directory.

#!/bin/bash
# grok - search file(s) for keyword
# Author: Gen2ly

# Text color variables
TXTBLD=$(tput bold)     # Bold
TXTUND=$(tput sgr 0 1)  # Underline
TXTRED=$(tput setaf 1)  # Red
TXTGRN=$(tput setaf 2)  # Green
TXTYLW=$(tput setaf 3)  # Yellow
TXTBLU=$(tput setaf 4)  # Blue
TXTPUR=$(tput setaf 5)  # Purple
TXTCYN=$(tput setaf 6)  # Cyan
TXTWHT=$(tput setaf 7)  # White
TXTRST=$(tput sgr0)     # Reset

if [ -z "$1" ]; then
  echo "grok <keyword> <location/file> - search file(s) for keyword (recursive)."
  exit
fi 

if [ -z "$2" ]; then
  echo "${TXTBLD}${TXTGRN} * ${TXTRST}Files found in ${TXTUND}`pwd`${TXTRST} that contain ${TXTYLW}"$1"${TXTRST}:"
  grep -Ilr "$1" `pwd` | sort | sed -e "s:`pwd`/::g"
  else
  echo "${TXTBLD}${TXTGRN} * ${TXTRST}Files found in ${TXTUND}"$2"${TXTRST} that contain ${TXTYLW}"$1"${TXTRST}:"
  grep -Ilr "$1" "$2" | sort | sed -e "s:$2/::g"
  exit
fi

cdf

This one is by segoe that uses locate to find a file and that cd’s to the first match found.

This one put in your ~/.bashrc:

cdf () { cd "$(dirname "$(locate -i "$*" | head -n 1)")" ; } # locate then cd

About Gen2ly

<3's linux

3 thoughts on “Week of bash scripts – grok and cdf

  1. Hollow says:

    grok can be simplified to:

    grep -Ilr “$1″ “$2″

    no need to call grep over and over again via find

  2. Gen2ly says:

    Thanks for the tip. Yeah, hadn’t thought of that, I’ll have to try it. Going to bed now though. :D

  3. Gen2ly says:

    Nice job, Hollow. Definitely a much better way of doing this. Updated the blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s