sometimes, grep alone is enough to do the task

April 14th, 2009 mysurface Posted in grep, Text Manipulation | Hits: 213564 | 3 Comments »

One thing that makes UNIXes command line so powerful is because of pipelines. Pipelines is a set of processes chained by their standard streams, so that the output of each process (stdout) feeds directly as input (stdin) of the next one. Simple words, pipelines pass the outcomes of a particular command as input to another command, and these chained allows you to do a command line combo!

A complex combo, I have constructed one last time in post what is your 10 common linux commands?

history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' |  \
grep -v "./" | \
column -c3 -s " " -t | \
sort -nr | nl |  head -n10

But sometimes we tend to misuse them, I found someone likes to do this:

cat foobar.txt | grep "barfoo"

Actually grep alone is enough to do the search, we do not need cat or meow for that. As I show him this:

grep "barfoo" foobar.txt

Another example is list the names of all files under a given directory that match a particular string. Let say I wanna obtain a list of files that have string "foobar".

find /opt/src/kmess -type f | xargs grep -l "foobar"

Hey! find is cool but grep alone is enough to do the job.

grep -lr "foobar" /opt/src/kmess

Try to go through the grep manual, you will find out that grep is more powerful than what you expect.

3 Responses to “sometimes, grep alone is enough to do the task”

  1. I dont think there’s anything wrong with cat file|grep “search term” under certain circumstances. If you’re going to continually grep the same file for various things it’s easier to cat it to a grep, it’s easier because you can change the search string faster as it’s at the end of the line instead of in the middle.

    If I was going to grep various files for one search term I would use grep “search term” filename, because now the filename is at the end. It’s all about context and the type of repetition.

  2. Some of us like to use smthn like this:
    grep “keyword” ./some.file | wc -l

    ..grep alone can do it:

    grep -c “keyword” ./some.file

  3. thank you

Leave a Reply