Searching Inside Text Files for Patterns


grep

The locate command searches the names of files and directories, but it can't search inside those files. To do that, you use grep. Essentially, you give grep a pattern for which you want to search, point it at a file or a group of files (or even a whole hard drive) that you want to search, and then grep outputs a list of lines that match your pattern.

$ grep pain three_no_more_forever.txt all alone and in pain 


In this case you used grep to see if the word pain was in a file containing a poem by Peter Von Zer Muehlen titled "Three No More Forever." Sure enough, the word pain is in the file, so grep prints the line containing your search term on the terminal. But what if you want to look in several of Peter's poems at once? Wildcards to the rescue!

$ grep pain * fiery inferno in space.txt:watch the paint peel, three_no_more_forever.txt:all alone and in pain the speed of morning.txt:of a Chinese painting. 8 hour a day.txt:nice paint job too ghost pain.txt:Subject: ghost pain 


Notice that grep finds all uses of the string pain, including paint and painting. Also pay attention to how grep shows you the filename for each file that contains the search term, as well as the line containing that term. So far, it's been pretty easy to search inside files with grep. So it's a perfect time to complicate matters, as you'll discover in the following sections.



Linux Phrasebook
Linux Phrasebook
ISBN: 0672328380
EAN: 2147483647
Year: 2007
Pages: 288

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net