1

I am new to Linux commands and I am trying to search for a word that say "apple" recursively in a directory and all the directory names that contain the word.

I am using ripgrep(rg) similar to grep to get the file names that have an apple in them

Ex:

rg -l "apple" 

gives me output:

a/fruit.c
b/fruit.c
a/fruits.c
a/fruitsnames.c
a/fruity/fruits.c
b/fru/fruit/fru/fr.c
c/frts.c

Is there a way that I can only the unique parent folder names?

Example output I expect is to get only the folder names:
a
b
c

Solution using grep is also good.

Thank you so much

oguz ismail
  • 1
  • 16
  • 47
  • 69
Red Gundu
  • 183
  • 2
  • 10

2 Answers2

4

use sed to remove everything from /, then use sort -u to remove duplicates

ripgrep -l apple | sed 's#/.*##' | sort -u
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you for the quick reply. I will give it a try :) Is there an efficient way to do this, say if you found one "apple" in a file in a directory then we can skip checking all the remaining files in that directory, as we only want to get the directory name? I think it would make it more faster – Red Gundu Jan 07 '21 at 21:56
  • Only if there's some way you can tell `ripgrep` to stop searching files once it has found a match. – Barmar Jan 07 '21 at 22:05
  • Then you could use `for dir in */; do ripgrep – Barmar Jan 07 '21 at 22:10
  • I can't find a complete list of flags in the ripgrep manual. It just has [Common Options](https://github.com/BurntSushi/ripgrep/blob/master/GUIDE.md#common-options) – Barmar Jan 07 '21 at 22:12
  • yeah, I also searched for it but couldn't find it. May be we can do it grep i will see. Thank you so much :) – Red Gundu Jan 07 '21 at 22:19
  • I don't think `grep` has an option like this. It has `-r` for recursive and `-m 1` to stop at the first match, but I think that's per file, not per directory. – Barmar Jan 07 '21 at 22:22
1

Use a Perl one-liner and sort -u so keep unique directories:

rg -l "apple" | perl -pe 's{/[^/]+$}{}' | sort -u

or to keep only the highest level directories:

rg -l "apple" | perl -pe 's{/.*}{}' | sort -u
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47