All Articles

The ABC's of grep - K

K

As many flags the grep command has, -K is not one of them. In fact if you try, you will see the following error:

$ grep -K
grep: invalid option -- 'K'
Usage: grep [OPTION]... PATTERNS [FILE]...
Try 'grep --help' for more information.

I thought this would be a good opportunity to see how to use grep with errors. Suppose we want to look for the word “information”. How would we do that?

Let’s take a look at the pipe operator | which can take the output of one command as the input of the next. Remember our test.txt file with the following content:

sad
happy
awake
coffee
work
school

Another way to search for “happy” is like this:

cat test.txt | grep "happy"
happy

In other words, we are taking the output of cat test.txt and using that as the input for grep happy.

So let’s try with our grep error:

$ grep -K | grep "information"

Unfortunately, this doesn’t work because grep -K produces an error stream. It can be tricky to understand at first but errors are treated differently than successful output. The grep command can operate on successful output (called standard out), but can’t use error output. We want to redirect the error to standard out (i.e. make the error something grep can operate on) and 2>&1 is how we do that.

Putting it all together, this is how we would search for terms in the grep error:

$ grep -K 2>&1 | grep "information"
Try 'grep --help' for more information.

Published Nov 7, 2023

I love coffee, coding and writing.