A better way to use grep to search files and folders. You do not need to use cat.

Posted: August 21, 2013. At: 7:29 PM

This is how to use grep to search a file without using cat.

[email protected]:~/Documents$ grep "gcc" ../.bash_history
gcc my.cpp
gcc hello.java 
gcc hello.java 
gcc hello.java 
gcc hello.java 
gcc mein.c -o mein
gcc -c99 mein.c -o mein
gcc -std=c99 mein.c -o mein
gcc hello.c -o hello
gcc hello.c -o hello
gcc hello.c -o hello
gcc hello.c -o hello

See? This works well enough without using cat. This is a very easy way to change a text file. This will take a word in the file and change it into another word.

[email protected]:~/Documents$ sed -i 's/Java/John/g' out.txt

Here I am searching all files in a directory for a specific word.

[email protected]:~/Documents$ grep -rl "Java" ./

it is not good to use cat unnecessarily. I have done it in the past; but I have seen the light and I will refrain from it in the future.

This example shows a tiny difference in resources usage when you refrain from using cat.

[email protected]:~/Documents$ time cat /etc/passwd | grep root

real	0m0.003s
user	0m0.000s
sys	0m0.000s
[email protected]:~/Documents$ time grep root /etc/passwd

real	0m0.002s
user	0m0.000s
sys	0m0.000s
[email protected]:~/Documents$

Here is a much larger difference when using grep against a 4 gigabyte file. The example without cat runs almost instantly.

[email protected]:/media/B8E69302E692BFD4$ time cat pagefile.sys | grep "windows 8"
Binary file (standard input) matches

real	0m4.155s
user	0m0.976s
sys	0m0.940s
[email protected]:/media/B8E69302E692BFD4$ time grep "windows 8" pagefile.sys
Binary file pagefile.sys matches

real	0m0.468s
user	0m0.248s
sys	0m0.104s
[email protected]:/media/B8E69302E692BFD4$

So I hope that these tips help you out and have fun with Linux!

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. For many bash scripts, cat is unnecessarily used. It should only be used when actually concatenating files or if you need test as stdin to pass through filters.