How can I force grep to only return files and ignore directories?
Asked Answered
G

4

6

I'm trying to use grep to automatically locate the bibtex program in the user's bin folder.

The problem is, it frequently returns a directory with the name bibtex, which means that the script fails to automatically run the command.

How can I force grep (or indeed the locate command) to automatically ignore directories?

EDIT: The current command is: locate bibtex | grep "/bibtex$" -d skip | head -n1

Gilmagilman answered 7/5, 2012 at 14:34 Comment(0)
H
12

The find command?

find /bin -name bibtex -type f

Looks for a file name "bibtex" of type "f", which is a regular file.

Hooch answered 7/5, 2012 at 14:37 Comment(2)
icecreamhead, accept this answer immediately, as your search is over :-)Hebephrenia
This answer does indeed work, but it takes much, much longer than locate, which isn't ideal in this situationGilmagilman
G
4
locate --basename '\bibtex' --limit 1

Eliminates the need for grep and head, but still doesn't solve the issue of whether the result is a directory.

Why don't you do:

type -P bibtex

which will look in the PATH for a program by that name?

Gaffney answered 7/5, 2012 at 14:44 Comment(0)
C
2

I don't understand exactly so maybe my solution is wrong: why don't you use which? Or bibtex isn't in PATH?

Cypsela answered 7/5, 2012 at 16:39 Comment(0)
D
1

Sigh, not my cleanest, but it works. perl -ne 'chomp($f=$_);print if !-d $f'

which makes your command locate bibtex | perl -ne 'chomp($f=$_);print if !-d $f' | grep "/bibtex$" -d skip | head -n1

Detached answered 7/5, 2012 at 15:1 Comment(3)
-d skip performs no action here since the input to grep is stdin. You can shorten your command to perl -ne 'chomp; print if ! -d'Gaffney
That was my first run of it, but I was unsure if the missing line-feeds would cause problems later down the pipe chain. I guess I'm a Nervous Nelly that way.Detached
By the way, you can shorten that to perl -lne 'print if !-d' (the chomp doesn't seem to be necessary, if it were then perl -lne 'chomp; print if !-d').Gaffney

© 2022 - 2024 — McMap. All rights reserved.