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

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

homer@neo:~/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.

homer@neo:~/Documents$ sed -i 's/Java/John/g' out.txt

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

homer@neo:~/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.

homer@neo:~/Documents$ time cat /etc/passwd | grep root

real	0m0.003s
user	0m0.000s
sys	0m0.000s
homer@neo:~/Documents$ time grep root /etc/passwd

real	0m0.002s
user	0m0.000s
sys	0m0.000s

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

homer@neo:/media/B8E69302E692BFD4$ time cat pagefile.sys | grep "windows 8"
Binary file (standard input) matches

real	0m4.155s
user	0m0.976s
sys	0m0.940s
homer@neo:/media/B8E69302E692BFD4$ time grep "windows 8" pagefile.sys
Binary file pagefile.sys matches

real	0m0.468s
user	0m0.248s
sys	0m0.104s

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

About Author

John Cartwright
Linux user that loves sharing all kinds of Linux information with the world. I love Linux and sharing information about how to use it and get the best out of your desktop is the best way to give back to the community.

1 Comment

  1. Hans Constantine

    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.


Leave a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>