Use command grep and locate
Asked Answered
P

4

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)

Paranoid answered 10/9, 2012 at 15:42 Comment(0)
J
16

Instead of a pipe, use command replacement:

grep user `locate my.cnf`
Jolin answered 10/9, 2012 at 15:48 Comment(2)
I like this one better than the xargs approach below because it maintains grep's highlightingEmotionality
@moeso: You can get grep to always give color output with --color=always.Litigant
L
17

Try:

locate my.cnf | xargs grep user
Litigant answered 10/9, 2012 at 15:46 Comment(3)
This option is correct, but Matt responded first and it works. Thanks.Paranoid
@Paranoid - if the result is fairly small, matt's works. If the result can be arbitrarily large, you should prefer xargs.Trichromatism
For options necessary for spaces in file paths, see answer of Marko Kudjerski below.Nowak
J
16

Instead of a pipe, use command replacement:

grep user `locate my.cnf`
Jolin answered 10/9, 2012 at 15:48 Comment(2)
I like this one better than the xargs approach below because it maintains grep's highlightingEmotionality
@moeso: You can get grep to always give color output with --color=always.Litigant
D
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
Dermato answered 10/9, 2012 at 15:54 Comment(3)
Shows the same output three timesParanoid
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.Dermato
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 userNowak
W
0

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

Wham answered 10/9, 2012 at 15:44 Comment(1)
Note that this will crash and burn if that locate command returns too much data. Command line size is not infinite.Litigant

© 2022 - 2024 — McMap. All rights reserved.