Search for a String Pattern in a File

$ cat apple.txt
core
worm seed
jewel
$ grep jewel apple.txt
jewel                                    
$ cat basket.txt
Layer1 = cloth
Layer2 = strawberries
Layer3 = fish
Layer4 = chocolate
Layer5 = punch cards
$ grep h basket.txt
Layer1 = cloth
Layer3 = fish
Layer4 = chocolate
Layer5 = punch cards                       
$ grep l basket.txt
Layer1 = cloth
Layer4 = chocolate
$ grep -i l basket.txt
Layer1 = cloth
Layer2 = strawberries
Layer3 = fish
Layer4 = chocolate
Layer5 = punch cards                
$ grep -v fish basket.txt
Layer1 = cloth
Layer2 = strawberries
Layer4 = chocolate
Layer5 = punch cards                
$ 

Another handy option of grep -w is to search for a string in a file as a word (that is, where it appears alone, with just non-letters before or after it). For example:

$ cat box7.txt
hamhocks + peas
ham sandwiches
gotham, new york + beans
ham+cheese
ham
anna=ham
$ grep -w ham box7.txt
ham sandwiches
ham+cheese
ham                                            
anna=ham
$

You can also use the single quotes to enclose strings with spaces. For example:

$ cat stuff.txt
rock + paper
scissors
fish
rock paper
sand + rock
paper + paper + scissors
roll +rock           
$ grep ' rock' stuff.txt
sand + rock
$ grep ' +rock' stuff.txt
roll +rock          
$ 

You can also look for strings containing special symbols such as ^ for the start of a line and $ for the end of a line. Continuing with the stuff.txt file as in the previous example, we can do this:

$ grep '^rock' stuff.txt
rock + paper
rock paper       
$ grep 'rock$' stuff.txt
sand + rock
roll +rock        
$ 

See also: egrep for searching for regular expressions.

Save this page to any social bookmarking site! Share · search Search · store Market · star Directory
2017-05-11 · John December · Contact · Terms of Use © December Communications, Inc.