Introduction to Linux shell commands
Chapter 3: Advanced Commands
Global Regex Print
grep is a very powerful tool that allows you to search for patterns in files. The grep utility searches any given input files, selecting lines that match one or more patterns.
By default, a pattern matches an input line if the regular expression in the pattern matches the input line.
note: This is not a tutorial on regex. For those interested I would point you towards this tutorial video and also to this regex cheat sheet
Nosy Josiah interrupts: We will cover regex in more detail later on in our course! kthxbye! *poof*
grep has the following structure.
grep [options] PATTERNS FILES
options allows you to specify how to search, see man grep for all the options - there are many! PATTERNS is the pattern you want to search for and FILES is where you want to search for
I have detailed some useful options below:
Exercise:
cd to /vol/bitbucket/hc-teaching/grep_demo. Here there are 3 .txt files to help demonstrate grep. Run the following commands:
- First use
catorlessto view the filenames.txt grep "John Williams" names.txtthe vanilla grep command, simply returns the lines in the filenames.txtwhich match the string"John Williams"grep -w "John Williams" names.txtonly matches whole words.grep -i "john williams" names.txtgrep is by default case sensitive, pass the optionito make it case insensitivegrep -n "john williams" names.txtthe option-nis useful as it returns the line numbers which matches were made.grep -C 2 "john williams" names.txtthis returns the match and +- 2 lines of context around the match.grep -win -C 2 "john williams" names.txtremember you can always combine arguments!grep -win "john williams" ./searches all files in the directory, this however, returns an error as there is a directory in your working directory. To combat this you can do:grep -win "john williams" ./*.txtutilises*which matches any content which ends with.txttherefore will not attempt to read the directorygrep -inr "john williams" .uses the recursive argumentrto recursively search down directories.
grep "...-...-..." names.txthere.specifies any character, so we are trying to match the patter 3x any character - 3x any character - 3x any charater.grep -P "\d{3}-\d{3}-\d{3}" names.txtif you want to use PERL compatible regex you need to specify the option-P