ABC to use grep to search for a word and also to get its line number

Wondering about the big title…. lolzzz… will it has a meaning….

First, The command :

cat filename | grep -n search_keyword | less

Say, you have a file called filename and you want to search for a term called search_keyword. The -n stands for number. It will print the line number where the search_keyword is found. | less is just a normal utility that lets you scroll up and down if you have the output (of the above command) running for more than a page.The following are some example –

Say, we have a file called abc.txt with the following contents:

A  :  mangoes are tasty fruits.
      Do u like mangoes ?
B  :  No, I don't.
      I like apples.
A  :  But I like mangoes more than apple.

From the shell (terminal), execute the following command.

cat abc.txt | grep mangoes

You will get the following output

A  :  mangoes are tasty fruits.
      Do u like mangoes ?
A  :  But I like mangoes more than apple.

When you added -n to the above command i.e.

cat abc.txt | grep -n mangoes

The output looks like this , notice the line numbers :

1:A : mangoes are tasty fruits.
2:    Do u like mangoes ?
5:A : But I like mangoes more than apple.

I hope everything is clear !
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: