ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Linux Guide: An Introduction to grep

Updated on April 13, 2009

A Brief Introduction

Linux is an operating system that is very powerful and offers many great tools. It is a free operating system and due to its reliability, is used as the backbone of the Internet.

When you need a new piece of software, whether it be a game, web browser,a Linux onscreen keyboard, or a Linux driver for your video camera, you can quickly and easily search for it and download it from the repositories. If you are using Ubuntu, it is simply a matter of firing up the Synaptic Package Manager and preforming a search using the name of the software or what it does.

For me, one of my favorite parts of Linux is how useful and powerful the command line, or terminal, is. There are literally thousands of different tools to do pretty much anything you could want, from converting audio or video files, to analyzing the security of a network.

One such command line tool that is very powerful and useful is grep. Which is typically used to search a file and find out where a specific phrase is. It can be very useful, especially when you are editing a new wordpress theme or working on a web server and need to find where a specific phrase is.This can be especially useful if you usea web host that allows you to SSH into their web server.

Technical Jargon Disclaimer

What follows includes a lot of Linux Specific Technical Jargon, so if you are unfamilar with Linux, it probably won't make too much sense.

The purpose of this Hub is to provide a grep tutorial, which provides a basic introduciton to the grep command. It will be followed up with a more advanced Hub that shows how to use some of the other many neat features of grep.

If you have any questions or can think of any improvements, please leave a comment.

Getting Started

Before we begin, lets make a text file to search. Open up your favorite text editor and copy the following information, including the Line Number, into text file.

Line 1: asdf
Line 2: pasta
Line 3: We the people of the United States of America
Line 4: How you have felt, O men of Athens, at hearing the speeches 
Line 5: of my accusers, I cannot tell; but I know that their 
Line 6: persuasive words almost made me forget who I was
Line 7: Lasagna 

Now, save the file as “test.txt” on your desktop. Open up a terminal and goto the desktop. If you are using Ubuntu, you can goto: Applications → Accessories → Terminal, type “cd Desktop,” and press return.

The Basics:

Lets start slowly and I will show you just a few of the ways you can use grep.

At its most basic, you can use two arguments; the word you are searching for and the file you want to search.

1. Type: grep pasta test.txt
 
   This should print: Line 2: pasta
 
 
2. Type: grep Lasagna test.txt 
 
   This should print: Line 7: Lasagna 

Showing the Line Numbers:

Now in our example, test.txt, we included the line numbers in our text file. However, in the real world you will seldom encounter this, but luckily grep includes a way of printing the line numbers, by including the “-n” option.

1. Type: grep -n pasta test.txt 
 
   This should print: 2:Line 2: pasta

 
2. Type: grep -n Lasagna test.txt
 
   This should print: 7:Line 7: Lasagna

Note that both times, the line number is printed first, followed by a full colon. Due tothe way hubpages does its formatting, your line numbers could vary though.

Showing the File Name:

One of the great things about grep is that you can use it to search multiple files at once. However, in the above examples, you would not be able to tell where the word came from. To show the file name, just add the -H option.

1. Type: grep -n -H pasta test.txt 
 
   This should print: test.txt:2:Line 2: pasta 
 

Note that it prints the name of the file, the line number of the phrase, and then the line that contains the phrase.

This next command is a little different and uses the '*' operator. In Linux, the '*' operator is used to match any phrase. In this context, we are telling grep to search any text file that is on your desktop.

2. Type: grep -n -H  Lasagna *.txt 

The results for number 2 will depend on how many text files you have on your desktop, that contain the word “Lasagna”, but it should at least print: “test.txt:7:Line 7: Lasagna ”

Ignoring Case:

As I am sure you know, Linux is case sensitive and by defualt so is grep. However, by including the -i command, you can tell grep to ignore the case of the letter.

1. Type: grep -n -H lasagna *.txt 

 
   This should not return any results, unless you happen to have
     a text file with lasagna in it. 
 
2. Type: grep -n -H -i lasagna *.txt
 

   This should print: test.txt:7:Line 7: Lasagna

Learning More:

These are just a few of the many ways that you can use grep. There are a number of other ways you can search a file or files using grep. I will do another Hub on advanced grep techniques shortly, but in the mean time, you can read the grep manual to learn more. Simply type “man grep” into the terminal to see the many options available.

Comments

Submit a Comment

  • brad4l profile imageAUTHOR

    brad4l 

    9 years ago from USA

    Thanks nicomp, great question!

    grep stands for Global Regular Expression Print and was originally a function in a text editor called "ed."

    In "ed", the "Global Regular Expression Print" function  was used to search files for specific patterns called regular expressions. For example, you could search the file for all words that start with the letter "a."

    Today, regular expressions still play a very important role in grep and are what makes grep such a powerful search tool. I intend to go into a little more detail on regular expressions and how they can be used in grep in one of my next few hubs.

  • nicomp profile image

    nicomp really 

    9 years ago from Ohio, USA

    Excellent intro to this useful utlility.

    I have heard several explanations for the acronym "grep";

    "General Regular Expression Processor", "General Regular Expression Parser", and others.

    Do you know the history of it?

  • brad4l profile imageAUTHOR

    brad4l 

    9 years ago from USA

    Thanks for stopping by and commenting rlakies. It takes some getting used to, but grep is a very powerful tool.

    Sorry to hear that you failed your Linux Certification, it can be a really nice thing to have on your resume as it can be very attractive to some potential employers.

    I find that I use it a great deal when I need to quickly find a piece of html or php code that might occur in a lot of different files. I think a lot of people who use shared hosting that allows them to SSH into their server, don't know the power that is available to them.

  • rlakies profile image

    rlakies 

    9 years ago

    i hate grep its always been a pain to use. no wonder i failed the linux cert :)

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)