Home RSS feed

 

Linux find

Here are a couple of find tricks I use repeatedly.

Search files

By declaring this function in e.g. ~/.bash_profile I can efficiently search files.

grip(){ find "${3-.}" -name '.[^.]*' -prune -o -name "${2:-*}" -type f -print0 | xargs -0 egrep ${@:4} "$1" ;}

I also set GREP_OPTIONS='--binary-files=without-match --color'

It skips all files and directories whose name starts with a dot. It works very much like wcgrep which I discovered later.

Usage: grip PATTERN [FILENAME_PATTERN] [DIRECTORY] [GREP_OPTIONS]...

Default FILENAME_PATTERN if not set or empty: *
Default DIRECTORY if not set: .

Examples:

grip somethingSearches all files in current directory for "something"
grip something \*.txtSearches .txt files
grip something '*.txt' /some/pathSearches .txt files in /some/path
grip something '' . -m 1Searches all files in current directory for first occurrence of "something"

Stop descent on first finding

Useful for finding outermost index.htm or pom.xml files, for example.

find -type d -execdir test -e {}/"$1" \; -print -prune

Find deepest directories (no subdirectories)

find -type d ! -execdir sh -c "find '{}' -maxdepth 1 -mindepth 1 -type d -print -quit | grep -q ." \; -print

This became more complex than anticipated. Because -execdir relies on exit code and find returns 0 (OK) on no results, I had to use grep, and because of the pipe, I had to use sh -c.

Another, faster, way is:

find -type d | awk 'NR>1 && $0 !~ "^" prev "/" { print prev } { prev=$0 } END { print }'

Grep log files

Here is a small program I wrote for easier grepping logfiles by printing the timestamp even if the matched line doesn't have one (e.g. stack traces).

awk -v "pattern=$1" '{
  if (match($0, /^[0-9][^[:alpha:]]*/)) {
    dat=substr($0, 1, RLENGTH)
    grep("")
  } else
    grep(dat)
}
function grep(prefix) {
  if ($0 ~ pattern) print prefix $0
}'

I also created a similar logcat.sh (nice with pipe from tail -f).

Tags: linux, bash, shell

Created on Thu, 20 Jun 2013 20:19

blog comments powered by Disqus