This page contains a description of how to filter text files and/or text output to the terminal screen.
Command Syntax
grep [options] PATTERN [file....]
Grep searches the specified input FILE (or standard input is no files are specified, such as if you pipe something to grep) for lines that contain a match to the pattern. By default, the matches are printed to the screen. You can also encapsulate the pattern in quotes ("PATTERN").
Options
-a, --text : This option allows you to process a binary file as if it was a normal text file. This is equivalent to the --binary-files=text option.
-c, --count : Suppress the normal output. Instead print the number of matches found.
-h, --no-filename : Suppress the prefixing of filenames on output when multiple files are searched.
-i, --ignore-case : ignore case in the pattern and file names
-l, --files-with-matches : Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
Examples
Example: In this example we search the file called README.txt for lines that contain the word 'help'
grep "help" README.txt
Example: In this case, no file is specified. We will search the directory /etc for all files that contain the word "cron" in the filename.
ls /etc grep cron
Basically, what we just did is perform a directory listing, only displaying lines that contain "cron". Using the "" (pipe), the output from the ls command becomes the input for grep.
Advanced Grep Usage
Grep can also be piped multiple times. For example, the output of one grep command can be the input for the second one, and so on.
For example, we want to check the mail log for all emails that were sent from ernie@company.com. First we "cat" the maillog, which would output every line in the file to the screen. This is more information than we want, so we pass the output along to our first grep command. We search for all lines that contain "ernie". The -i option is used to ignore the case. So far, the syntax would be:
cat /var/log/maillog grep -i ernie
We are partially there. The result from this command outputs every line containing "ernie". But this also includes all places where ernie was the recipient as well as the sender. Next we filter out only the places where he was the sender:
cat /var/log/maillog grep -i ernie grep from
The output from this command lists all places in the mail log pertaining to ernie sending an email.
Josh's Example:
cat maillog grep "Dec 11" egrep "TO:<\w+@domain.com" -c
First I filtered out the maillog for entries of a certain day, then I filtered for entries:TO:ANYUSER@company.com
the -c command will only display the number of occurrences.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment