hack

Breadth-first search grep

Firmin Martin
· Reading time: 1 min.· Updated Saturday, July 11th, 2026
clishelllinux

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

    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.

    Footnotes

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