--- layout: page author: Domenico Votta category-page: advanced category-title: Advanced commands tags: search for occurences title: grep ---
The grep
is a command that permits to search occurences of a keyword or more in a file or more. Through some flags you can decide the search criteria. The command grep is case sensitive (robot is different from Robot), but we will see how to ignore it
example1.txt
and example2.txt
that contain 5 elements, to test this command:
example1.txt
{% highlight bash linenos %}
Car
Computer
Robot
Smartphone
Videogame
{% endhighlight %}
example2.txt
{% highlight bash linenos %}
Apple
Computer
Robot
Microsoft
Huawei
{% endhighlight %}
The syntax command is:
grep [flag] [keyword] [file]You can put different flags together to refine the search. {% highlight ruby linenos %} grep Robot example1.txt example2.txt (if you write robot you won't have the correspondence.) example1.txt: Robot example2.txt: Robot {% endhighlight %}
Your output will be this because grep found the keyword Robot in both files
Here a list that contains the main flags of these command:
grep -i robot example1.txt example2.txt example1.txt: Robot example2.txt: Robot
grep -i -v robot example1.txt example2.txt example1.txt:Car example1.txt:Computer example1.txt:Smartphone example1.txt:Videogame example2.txt:Apple example2.txt:Computer example2.txt:Microsoft example2.txt:Huawei
grep -i -c robot example1.txt 1
If in the file you would have had two times the keyword Robot, the output would have been 2
grep -i -h apple example1.txt example2.txt Apple
How you can see the output doesn't show tha file name example2.txt