This page looks best with JavaScript enabled

Breadth-first search grep

 ·  ☕ 1 min read  ·  ✍️  Firmin Martin

Introduction

From time to time, I want to search over my dotfiles, precisely those immediately under my home directory ~/. The problem of grep -R <regex> is that it quickly delves into an oceanic trench, full of caches, xml files or databases. In other words, it uses a depth-first approach.

bfs-grep

The following shell function helps me greatly to deal with such a situation. It employs a breadth-first search, i.e. level by level. It is written for zsh but should work for bash or ksh931. The tput commands are just used to redden the level announcement. Further tweaks can be made such as changing the dot . (current directory) to a target directory or starting from a specific level. But that’s enough for me.

1
2
3
4
5
6
function bfs-grep {
    for i in $(seq 1 $1); do
        >&2 echo "$(tput setaf 1)BFS-GREP: LEVEL $i$(tput sgr0)"
        find . -mindepth $i -maxdepth $i -type f -exec grep "${@:2}" {} +;
    done
}

Usage

bfs-grep first argument is the maximum depth to search, starting from 1 for the current level. The remaining arguments are fed to grep.


  1. See here for ${@:2}↩︎


Firmin Martin
WRITTEN BY
Firmin Martin

What's on this Page