Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell : Interactive Fuzzy-Search content in files using grep and fzf

Tags:

grep

fzf

I want to write a shell script that search for a pattern inside all the files in a specific directory (say, my '.config' folder). Using grep I wrote the following:

grep -Ril "<pattern>" .config

Next I was trying to change the search pattern on the fly using something like:

grep -Ril "" .config | fzf --preview='<preview> {}'

, but since I'm passing the filename to fzf - I can only filter the results by names...

Basiclly I'm looking for something like:

grep -Ril "<fzf_pattern>" .config | fzf --preview='<preview> {}'
like image 231
David Delarosa Avatar asked Sep 14 '25 02:09

David Delarosa


2 Answers

see this little script which you can name as fzgrep:

#!/bin/bash
set -euo pipefail
# go get github.com/junegunn/fzf

BEFORE=10
AFTER=10
HEIGHT=$(expr $BEFORE + $AFTER + 3 )  # 2 lines for the preview box and 1 extra line fore the match

PREVIEW="$@ 2>&1 | grep --color=always -B${BEFORE} -A${AFTER} -F -- {}"

"$@" 2>&1 | fzf --height=$HEIGHT --reverse --preview="${PREVIEW}"

and use it as follows: fzgrep cat /var/log/syslog

like image 68
giulianopz Avatar answered Sep 16 '25 17:09

giulianopz


You can do:

grep -R "$(find .config/* -type f -exec cat {} \; | fzf)" .config/
like image 21
mattb Avatar answered Sep 16 '25 17:09

mattb