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
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" ./
./script2.html
./clock2.htm~
./a.out
./script1.html~
./HelloWorld.java
./script1.html
./clock3.htm~
./script2.html~
./clock2.htm
./clock3.htm
./HelloWorld.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
root:x:0:0:root:/root:/bin/bash

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

real	0m0.002s
user	0m0.000s
sys	0m0.000s
homer@neo:~/Documents$

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
homer@neo:/media/B8E69302E692BFD4$

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

One thought on “A better way to use grep to search files and folders. You do not need to use cat.”

Leave a Reply

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=""> <strike> <strong>

Current day month ye@r *