10

How I can make the grep command locate certain words in the files specified by the routes found by the locate command?

locate my.cnf | grep user

(I want that grep command search the word "user" on the files found for locate command)

Jhonathan
  • 1,611
  • 2
  • 13
  • 24

4 Answers4

17

Try:

locate my.cnf | xargs grep user
cha0site
  • 10,517
  • 3
  • 33
  • 51
16

Instead of a pipe, use command replacement:

grep user `locate my.cnf`
matt b
  • 138,234
  • 66
  • 282
  • 345
2

In order to play nice with situations when locate results have spaces in names, you could do this

locate -0 my.cnf | xargs -n1 -0 grep user
Marko Kudjerski
  • 348
  • 2
  • 4
  • Shows the same output three times – Jhonathan Sep 10 '12 at 16:04
  • Without any switches `grep` automatically outputs all of the matching lines (your file likely has multiple lines that match). If you wish to show line numbers in front of them you could use `-n` switch for grep. Otherwise, you could have it output only the first match for every file with `-m 1` or only the name of the file that matches with `-l`. – Marko Kudjerski Sep 11 '12 at 14:55
  • `locate -0` is indeed necessary if file paths contain spaces. However, in bash, to see the full path of the file, I have to add `-H` to grep, like so: `locate -0 *.tex | xargs -n1 -0 grep -H user` – Markus Jun 17 '23 at 14:52
0

Probably grep user $(locate my.cnf) is what you're looking for, if I understand your question correctly.

lanzz
  • 42,060
  • 10
  • 89
  • 98
  • 4
    Note that this will crash and burn if that `locate` command returns too much data. Command line size is not infinite. – cha0site Sep 10 '12 at 15:47