Sample Header Ad - 728x90

Display `grep -lr` results as a tree

2 votes
1 answer
917 views
I'm searching a large number of text files which are organized in various subdirectories. I can run a command such as grep -lr foobar ./, and I get results like the following:
./dirA/dirA.A/abc.txt
./dirA/dirA.A/def.txt
./dirA/dirA.A/dirA.A.A/ghi.txt
./dirA/dirA.B/jkl.txt
./dirB/mno.txt
I would like some way to display these in a visual tree, similar to how the tree command works. Something roughly like this:
./
  dirA/
    dirA.A/
      abc.txt
      def.txt
      dirA.A.A/
        ghi.txt
    dirA.B/
      jkl.txt
  dirB/
    mno.txt
It seems like it'd be trivial to do this in some Python script with a stack, but I'd really like some way to do this straight from bash if there's a way to do it. So I guess I'm looking for a way to either (a) format/transform the output of grep, OR (b) some other generic "indent-by-common-prefix" utility that I've so-far been unable to find.
Asked by loneboat (241 rep)
Mar 16, 2022, 04:43 PM
Last activity: Mar 17, 2022, 05:32 PM