Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

grep

grep is a vital part of the Unix/Linux toolbox. It searches its input for lines that match the regular expression passed to it. In its simplest (and most common) usage, it is used to search for a fixed string, in which case the flags are more significant than the regular expression functionality of grep. grep’s regular expression grammar is described later in the chapter in the section “Grep Regular Expressions.” grep is such a common command that you can find it in many of the code examples in this book, even when it is not being addressed directly. This section provides some examples of how it can be used in some more and less common ways, and explains what grep is capable of.

grep Flags

The four most commonly used flags to grep are -i (case-insensitive search), -l (list only the names of matching files), -w (which matches whole words only), and -v (invert; this lists only the lines that do not match the pattern). Another less well-known flag that is rather useful is -e. This can be used to pass multiple search patterns on a single command line. grep -e replaces egrep as the preferred way to search for many patterns at once. The following example uses a contacts list (contacts.txt) with a fixed structure, such that each contact has four lines associated with it and each line contains one field. Apart from that, nothing else is fixed — there could be any other text in the file, and spacing could be padded in any way. These four flags can be tested quite effectively.

 $  ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads