Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 447
icecreamhead Avatar asked May 07 '12 14:05

icecreamhead


People also ask

How do I grep only files?

Since many files contain database references, you might get a lot of data on output, so if you are only interested in all the files containing matching text, you can use the grep -l option. This option of grep only shows filenames that contain matching text.

How do I exclude a directory from recursive grep?

You would need --exclude-dir="dir1" , which excludes elsewhere/dir1 as well. Note that if a directory is excluded, its subdirectories are excluded as well, so --exclude-dir="dir1" also excludes files in . config/dir1/dir2 . If grep's exclude patterns aren't sufficient for you, you can combine find with grep .

How do you exclude a directory?

Go to Start > Settings > Update & Security > Windows Security > Virus & threat protection. Under Virus & threat protection settings, select Manage settings, and then under Exclusions, select Add or remove exclusions. Select Add an exclusion, and then select from files, folders, file types, or process.

How do I exclude a file type in grep?

To read a list of files to exclude from a file, use --exclude-from FILE .


2 Answers

The find command?

find /bin -name bibtex -type f

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

like image 123
Stephen Darlington Avatar answered Oct 31 '22 01:10

Stephen Darlington


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?

like image 45
Dennis Williamson Avatar answered Oct 31 '22 02:10

Dennis Williamson