4

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> {}'
Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
  • You might want to create an issue on the `fzf` repo and ask this question. The developer might help you out :) – Siddharth Dushantha Feb 04 '20 at 18:41
  • 1
    Check this: https://github.com/junegunn/fzf/wiki/Examples#searching-file-contents fuzzy search content of a file. – Tuyen Pham Jun 20 '20 at 07:40
  • You want to check this out: https://github.com/Genivia/ugrep fuzzy search files, directories, compressed archives etc. Just execute `ugrep -Ril -Z "" .config` – Dr. Alex RE Jun 30 '20 at 15:17
  • There is no "Linux Shell", you're probably using Ash or Bash, but there are many other shells and many of them work on other kernels, not just Linux. – Ulrich Eckhardt Apr 09 '21 at 11:21

3 Answers3

1

You can do:

grep -R "$(find .config/* -type f -exec cat {} \; | fzf)" .config/
mattb
  • 2,787
  • 2
  • 6
  • 20
1

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

giulianopz
  • 184
  • 1
  • 8
0

Some have suggested to use ugrep for fuzzy matching with a grep-based tool, like so:

ugrep -Q -Z+4 -Ril .config

-Q starts a query UI in your terminal to enter a fuzzy pattern and -Z+4 fuzzy-matches up to 4 extra characters. You can also play with the -Z values in the UI by pressing Alt-[ to decrease and Alt-] to increase fuzziness. Press F1 or Ctrl-Z for a help page. To obtain the list of matching files sorted by best match, add the option --sort=best.

Dr. Alex RE
  • 1,772
  • 1
  • 15
  • 23