grep command in linux process text line by line and print any line which matches our specified pattern. Grep - Global Regular Expression Print.
grep command in linux with flag and examples
![]() |
grep command in linux |
Hello guys, In this session, you will learn how to use the "grep" command in Linux.
"grep" stands for "Global Regular Expression Print".
grep command process text line by line and print any line which matches our specified pattern.
So "grep" command can be used to search for patterns or words or sentences in a text file.
Let's see how you can use the grep command,
To search words
![]() |
search words |
$grep "enter your searchTerm" fileName
I want to search for the word "example". So I just write 'grep "example" file1.txt' and then press ENTER.
Now you can see it has searched the line which are containing the keyword "example".
[-i] flag with grep
![]() |
with I flag |
$grep -i "enter your searchTerm" fileName
This "grep" command is case sensitive by default. But you can use "-i" flag to make it case insensitive.
So if you use "-i" flag then it's going to search for capital (or) small letter words when you press ENTER.
To print line number
![]() |
print line number |
$grep -n "enter your searchTerm" fileName
I want to print the line number and then the result. So I can use the "-n" flag. This "-n" is for printing the line number.
Just write 'grep -n "example" file1.txt' and press ENTER.
It's going to print the line number with the result.
Search with multiple files
![]() |
search with multiple files |
$grep "enter your searchTerm" file1 file2 ...
So you can also use the "grep" command to search with multiple files.
You just need to write 'grep "example" file1 file2 file3' and then press ENTER.
And now you can see it's going to print the name of the file and result.
Search with all files in the current folder
![]() |
using wild card |
$grep "enter your searchTerm" *
In the above command, you have to type all the file names. This can be made simpler with a wild card.
So instead of writing this, you can use an asterisk (*) it means to search with all the files in this folder.
So just write 'grep "example" *' and press ENTER.
It's going to search and print the result.
Inverse search
![]() |
Inverse search |
$grep -v "searchTerm" fileName
If you want to search in an "inverse" manner. The line which doesn't contain "search term". In this case, you can use a flag "-v".
Whenever you use this "-v" flag with grep it shows all the lines which don't contain this "search term".
Conclusion
There are many are flags and options which you can use with the "grep" command. I show you only the frequently used flags in grep command.
I hope you enjoyed this tutorial, Thanks.
HAVE A NICE DAY💗
Related,