27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

# /var/log/messages must have world read permission for this to work.<br />

echo "$filename contains tail end of system log."<br />

exit 0<br />

grep<br />

See also Example 12−4, Example 12−30 and Example 30−6.<br />

A multi−purpose file search tool that uses regular expressions. It was originally a command/filter in<br />

the venerable ed line editor, g/re/p, that is, global − regular expression − print.<br />

grep pattern [file...]<br />

Search the target file(s) for occurrences of pattern, where pattern may be literal text or a<br />

regular expression.<br />

bash$ grep '[rst]ystem.$' osinfo.txt<br />

The GPL governs the distribution of the Linux operating system.<br />

If no target file(s) specified, grep works as a filter on stdout, as in a pipe.<br />

bash$ ps ax | grep clock<br />

765 tty1 S 0:00 xclock<br />

901 pts/1 S 0:00 grep clock<br />

The −i option causes a case−insensitive search.<br />

The −w option matches only whole words.<br />

The −l option lists only the files in which matches were found, but not the matching lines.<br />

The −r (recursive) option searches files in the current working directory and all subdirectories below<br />

it.<br />

The −n option lists the matching lines, together with line numbers.<br />

bash$ grep −n Linux osinfo.txt<br />

2:This is a file containing information about Linux.<br />

6:The GPL governs the distribution of the Linux operating system.<br />

The −v (or −−invert−match) option filters out matches.<br />

grep pattern1 *.txt | grep −v pattern2<br />

# Matches all lines in "*.txt" files containing "pattern1",<br />

# but ***not*** "pattern2".<br />

The −c (−−count) option gives a numerical count of matches, rather than actually listing the<br />

matches.<br />

Chapter 12. External Filters, Programs and Commands 166

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!