DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Edited on

How to exclude long lines in your grep results?

When we grep for anything on a Mac or Linux:

grep -ri ContactComponent . 
Enter fullscreen mode Exit fullscreen mode

the output can have really long lines, from the "compiled output" or the webpack results. To filter out those results, we can add an alias to our Bash .bashrc:

alias excludelonglines='grep "^.\{0,300\}$"'
Enter fullscreen mode Exit fullscreen mode

So then we can do:

grep -ri ContactComponent . | excludelonglines
Enter fullscreen mode Exit fullscreen mode

in the future. It will exclude any lines that are more than 200 characters long for you.

If you want, you can name the alias exlong instead, to make it easy for typing. Or on many systems, you can type excl and press the tab key, and if you don't have other alias or command that starts with excl, it will auto-complete for you. In fact, nowadays I just simply alias it as:

alias excl='grep "^.\{0,300\}$"'
Enter fullscreen mode Exit fullscreen mode

so I can do

grep -ris ContactComponent . | excl 
Enter fullscreen mode Exit fullscreen mode

I recommend using at least 300 as the length, because when the first grep result is obtained, the file name and path is already there, which could easily take up 80 or 100 characters, so if you do:

grep -ris ContactComponent . | grep import | excl 
Enter fullscreen mode Exit fullscreen mode

then your excl is only including the lines that are about 200 characters long. If you use 200 in the alias, then the length is 100 characters long and you may miss something if it happens somebody has a line that is 120 characters long.

Sometimes, there can be error messages that make the output messy (such as soft link not exists, etc, which sometimes happen to ./node_modules). In such case, you can use

grep -ris ContactComponent . | excl 
Enter fullscreen mode Exit fullscreen mode

to silence the errors. Or redirect stderr to /dev/null:

grep -ri ContactComponent . 2> /dev/null | excl 
Enter fullscreen mode Exit fullscreen mode

or

grep -ri ContactComponent . 2>&- | excl 
Enter fullscreen mode Exit fullscreen mode

The 2 above is the file descriptor for the standard error stderr. /dev/null is the "null device" (also called the bit bucket or black hole). The >&- is to close the file descriptor, and 2>&- is to close stderr.

Top comments (0)