DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Updated on

How to exclude long lines in your grep results?

When we grep for anything on a Mac or Linux:

grep -ri ContactComponent . 

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\}$"'

So then we can do:

grep -ri ContactComponent . | excludelonglines

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\}$"'

so I can do

grep -ris ContactComponent . | excl 

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 

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 

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

grep -ri ContactComponent . 2> /dev/null | excl 


grep -ri ContactComponent . 2>&- | excl 

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.

Discussion (0)