Searching for text within file contents

Searching for text within file contents in Linux

When you want to do this, odds are, you know what kind of file you are looking for, My first guess would be you would not be looking in zip, mp4, flv, etc… those are huge files, where in the unlikely event they do contain your string, it’s still not the file you are looking for…

So, you would probably want to look at the problem as, search the contents of text files for a certain text string

the best way to acheive that is to start by allowing the find command to find text files that may contain that string, then passing the “candidate for searching” files to the grep command

So if I am looking for a config file that contains a config named living-room, I would use a search such as this one

find /hds -name '*.conf' -exec grep -i 'living-room' {} \; -print

What is nice about this is that you can also look at both separately, so the find command has plenty of documentation online, and so does grep

Now, there are other ways to do this, the most popular of which is using grep on it’s own, here are some examples

The directives are as follows

i stands for ignore case (Slows things down, but sometimes necessary).
R stands for recursive. (Look inside inner folders depth first)
l stands for "show the file name, not the result itself".
e look for things matching a patern
--include Include files that match this pattern
--exclude Exclude files that match this pattern
--exclude-dir exclude directories listed
grep -Ril "text-to-find-here" /
grep --include=*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
grep --exclude=.o -rnw '/path/to/somewhere/' -e "pattern" grep --exclude-dir={dir1,dir2,.dst} -rnw '/path/to/somewhere/' -e "pattern"

Hope this helps, good luck

Leave a Reply

Your email address will not be published. Required fields are marked *