Eren Akbulut's Blog

Unix Commands V - grep

January 26th, 2021

Hello everyone today I'll add another page to the Unix Commands series with grep command, so without further ado let's dive right into the topic


What is grep?

The grep commands stands for Global Regular Expression Print. It helps us to find strings in large directories and even recursively. It's quite straightforward to use and absolutely powerful. Now let's take a look at some examples.


unix-grep-cat

This file is one of the main ones we'll use through that tutorial and consist those lines. Now let's move to first example.

unix-grep-basic

The 4 commands above does the following thing respectively.

  • The grep takes the target string and target positionally and runs the search then brings the results

  • With -w flag however it only prints the exact match, not if the target string is also a part.

  • If we put * instead of a certain file, it'll search for all the files in current directory.

  • We can apply the same -w flag with this * technique also.

unix-grep-basic-insens
  • grep normally works case sensitive so if we need to turn that feature of we can instead add -i flag to avoid case check.

unix-grep-r
  • When we need to expand our search to sub directories we can use -r flag to search sub directories recursively. It'll show what and where were the strings matches found.

unix-grep-whole
  • The -x flag is to look for matches with longer strings. If the match in a sub directory when the -r flag hasn't used we can face up with such an error.

unix-grep-inverse
  • We can use the -v flag to perform inverse searches, here in the examples we search for all the lines without the string "Orange" in them.

unix-grep-count
  • The last one I'll show today is the -c flag. With the -c we can count the appearances of the target string in the target location.


Alright everyone, that was it today. I tried to mention briefly about the some main use cases of the grep command. You can check it the further use of it here. You can also try different use cases with the use of pipes if you check the older posts of the series.

I hope to see you in the next one.

This blog has been created by Eren Akbulut 2020