lsgrep is just a simple tool I use to quickly find files matching a search pattern in the current directory. I just figured I’d share it because I end up using it a lot.
My primary shell is Fish, so I’ll share that one first. This version uses silver searcher (ag) to search for matches. The search uses wildcards (* for multiple characters and ? for a single character). Spaces get turned into .*? and extensions (e.g. .sh) get escaped so the period matches.
# Defined in /Users/ttscoff/.config/fish/functions/lsgrep.fish @ line 1
function lsgrep --description 'Wildcard folder/file search'
# Convert search to regex: change .X to \.X, ? to ., and space or * to .*?
set -l needle (echo $argv|sed -E 's/\.([a-z0-9]+)$/\\\.\1/'|sed -E 's/\?/./'| sed -E 's/[ *]/.*?/g')
command ag --hidden --depth 3 -SUg "$needle" 2>/dev/null
end
Now I can run lsgrep in Fish like this:
This will find the file gist_test.sh in any subdirectory up to 3 levels deep from the current directory.
Here’s a version in Bash (or Zsh) that uses find instead, requiring no extra tools:
#!/bin/bash
NEEDLE=".*$(echo $@|sed -E 's/\.([a-z0-9]+)$/\\\.\1/'|sed -E 's/\?/./'| sed -E 's/[ *]/.*/g').*"
find -E . -maxdepth 3 -regex $NEEDLE 2>/dev/null
Because find doesn’t allow for .*? operators in the regex, it’s a little bit broader of a search, but in 99% of cases the results are the same as the ag version.
You can obviously change the max depth in either function to a higher number if you want to search deeper in the directory tree.
Hope that’s useful!