DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for grep command [ Linux tips ]
Nuwan Karunarathna
Nuwan Karunarathna

Posted on

grep command [ Linux tips ]

Grep command can be used to filter or search text from files or input streams.

Basic usage,

grep β€œtext_to_search” fileToSearch

In here the β€œtext_to_search” can be a plain string or a regular expression.

Example 1

Assume that we need to find whether the text β€œuser login failed” has appeared in a log file. Then we can use the grep command like below.

grep β€œuser login failed” logFile.txt

After running the above line grep will print the lines of text which includes the text β€œuser login failed”.

Another very useful way we can use grep command is to filter out input streams like the output of another command (or another grep command).

Example 2

Let’s say you want to find out whether a file is there in a folder which contains like 1000 other files. We can simply use the grep command to find out that like below.

ls | grep β€œfile_name_to_find”

In here the β€˜|’ (pipe) will send the output of the ls command as an input to the grep command(but it’s not a grep specific operator).

So these are the most common ways we can use grep to make our lives easier and it has limitless usages but grep has many more options too. Below are some of the options we can use.

-n : prints the line number
-o : prints only the matching part of the text
-c : prints the number of matches

Example 3

If we want to know how many files have the name as the file name in the above example we can simply use the -c option.

ls | grep -c β€œfile_name_to_find”

Top comments (1)

Collapse
 
princessanjana1996 profile image
PrincessAnjana1996

It's very useful and I like it.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.