grep Command in CLI

Baransel - May 2 '22 - - Dev Community

Sign up to my newsletter for more tutorials!.

grep, the global regular expression print, allows us to select and/or mark from a text stack in the context of the specified pattern. The entered template is processed within the specified path, results suitable for the template are listed by marking. By using it alone or with pipes |, its capabilities can be developed and/or evaluated in different-purpose operations.

The simplest use by itself is as follows.

grep '[search-text/pattern]' [path-to-directory-or-file]
Enter fullscreen mode Exit fullscreen mode

We can move on to examples. I will use the access_log.txt document of the web server for operations. I want to extract only POST operations from the text stack. So I can use a command like this.

grep 'POST' /home/nginx/access_log.txt
Enter fullscreen mode Exit fullscreen mode

What if I want to perform an exclude operation instead of a select operation? For example, I want to list the transactions that took place outside the 5.12.88.10 IP address.

grep -v '5.12.88.10' /home/nginx/access_log.txt
Enter fullscreen mode Exit fullscreen mode

Let's develop the example a little more. Let's filter the search operations and direct them to the keywords.txt file with >. Unless otherwise stated, operations will be performed in the context of case sensitivity. In the example, I applied the command by specifying -i to execute the operation without case distinction.

grep -i 'search' /home/nginx/access_log.txt > /home/nginx/keywords.txt
Enter fullscreen mode Exit fullscreen mode

There are also parameters and usage methods that we can use in line marking, file name and content search operations. Of course, it is possible to get more detailed information with grep –help. However, to give a short summary; Using the -n parameter, we can get the line number of matches that match our search pattern inside a file. Using it with cat, we can cast the fields we want with head and tail.

cat -n /home/nginx/access_log.txt | grep "spam"  | head -5
Enter fullscreen mode Exit fullscreen mode

As seen in the example, we do not need to apply the grep command first. It is possible to continue many related operations in grep after the pipe (|) mark.

ls -alh | grep '.sql'
Enter fullscreen mode Exit fullscreen mode

With the above command, the lines containing .sql will be listed and marked. You can edit the command with directories (^d) and files (^-).

Sign up to my newsletter for more tutorials!.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player