Searching and mining a text inside a file with grep
Searching inside a file is an important use case in text processing. We may need to search through thousands of lines in a file to find out some required data, by using certain specifications. This recipe will help you learn how to locate data items of a given specification from a pool of data.
How to do it...
The grep
command is the magic Unix utility for searching in text. It accepts regular expressions, and can produce output in various formats. Additionally, it has numerous interesting options. Let's see how to use them:
To search for lines of text that contain the given pattern:
$ grep pattern filename this is the line containing pattern
Or:
$ grep "pattern" filename this is the line containing pattern
We can also read from
stdin
as follows:$ echo -e "this is a word\nnext line" | grep word this is a word
Perform a search in multiple files by using a single
grep
invocation, as follows:$ grep "match_text" file1 file2 file3 ...
We can...