The proper way to use grep without cat. And some nice tricks.

Posted: October 1, 2017. At: 9:55 PM. This was 2 months ago. Post ID: 11425
Page permalink.
WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters. These cookies expire two weeks after they are set.

This is the proper way to use grep. You do not need to use cat at all. This method works well and is one command, not two piping together.

jason@jason-desktop:~/Documents$ grep apt-get ../.bash_history
sudo apt-get update
sudo apt-get install me-tv
sudo apt-get update && sudo apt-get install xvst
apt-get moo
apt-get moo

This is how to count the occurrences of the search string in a file.

jason@jason-desktop:~$ grep -c "ssh" .bash_history 
10

It does not even matter if the user is not sure if the search string desired is upper case or lower case. The -i parameter allows searching for a string that is any combination of upper or lower case letters.

jason@jason-desktop:~$ grep -i "APT-GET" .bash_history 
sudo apt-get update
sudo apt-get install me-tv
sudo apt-get update && sudo apt-get install xvst
apt-get moo
apt-get moo

This is how to only return the search string you were looking for. Use the -o parameter to only show the search result string.

jason@jason-desktop:~$ grep -o -i "Snowbox" magik-1.txt 
SnowBox
SnowBox

Does the user want to know which line of the file the search result is on? Then use the -n parameter. This prepends line numbers on to the results.

jason@jason-desktop:~$ grep -o -n -i "Snowbox" magik-1.txt 
735:SnowBox
736:SnowBox

This is very useful for finding an entry in a very long text file.

No comments have been made. Use this form to start the conversation :)

Leave a Reply