3

The fzf examples wiki page describes how fzf can be used to fuzzy search within the content all the files of a directory. But in the examples from the wiki page, e.g. with

ag --nobreak --nonumbers --noheading . | fzf

the files are split up by their lines and each line is treated separately.

For example a file:

hello
world

wouldn't match the search term "hello world" because the search terms are in different lines.

How can I use fzf so that it searches within the whole file and not only by lines?

1
  • Never used ag, so I'm not sure, but how about piping the output of ag through something like tr '\n' ' ' first to convert all the newlines to spaces? The output would be quite unwieldy, but it should work. It really depends on what you want to do once fzf finds something for you. Depending on your ultimate goal, something like sed or grep might work better - although less interactively.
    – Joe
    Apr 8, 2020 at 11:38

1 Answer 1

1

I have a somewhat dirty solution.

rg --heading --glob "*.txt" . some_directory_path | sed 's/^$/NEWLINEHEREYO/g' | tr '\n' ' ' | sed 's/NEWLINEHEREYO/\n/g' | fzf

explanation:

when you do

rg . 

somewhere, it prints output to terminal in a specific format that gets lost if you try to pipe it somewhere. I find the format is necessary to be able to do this efficiently. Hence, the --heading flag which maintains the format. --glob and the directory I added just because I did it in my own usecase, and I did not want to modify the command lest it break - I'm not that good with computers.

It then replaces all the empty lines, which delimit files, with the NEWLINEHEREYO tag using sed. It then truncates all the newline characters (which would destroy the empty lines) using tr, giving a single-line output, which is what you wanted. It then reintroduces the breaks with another sed command by converting the NEWLINEHEREYOs back to line breaks so fzf doesn't search it as if it was literally a single line.

It's very inefficient, but works ok for my usecase. I reckon the sed, tr and sed commands can probably be merged into one, but I'm too stupid to do it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .