Week of bash scripts – grok and cdf

These two scripts are two different find commands. The first (grok) will list all files in a directory recursively that contain a matched string; 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 <string> <*location>

If no location is given it uses the current directory.

aspire ~:
grok 127.0.0.1 /etc/
 Searching...
/etc/dnsmasq.conf
/etc/dnsmasq.conf.pacorig
/etc/hosts
/etc/NetworkManager/dispatcher.d/localhost-prepend
/etc/ntp.conf
/etc/resolv.conf
/etc/security/access.conf
/etc/xinetd.d/servers
/etc/xinetd.d/services
#!/bin/bash
# Search file(s) for keyword
# Display usage if no parameters given
if [[ -z "$@" ]]; then
echo -e " ${0##*/} <string> <file/path> - search recursively for keyword in files"
exit
fi
if [ -z "$2" ]; then
loc=$(pwd)
else
loc="$2"
fi
echo " Searching..."
grep -ilr "$@" "$loc" 2>&1 | grep -v "No such" | grep -v "Permission denied" | sed "s:^\.::g" | sed "s:$(pwd)::g" | sort | uniq
view raw grok hosted with ❤ by GitHub

cdl

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

aspire ~/.scripts:
cdl demo/PKG
aspire ~/.arch/pkgbuilds/amnesia-demo:

This one put in your ~/.bashrc:

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

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

  1. Hollow

    grok can be simplified to:

    grep -Ilr “$1” “$2”

    no need to call grep over and over again via find

    Reply

Leave a comment