Archiv für die Kategorie ‘grep’

Lesser known uses of grep

23. Oktober 2016 Keine Kommentare

In this article i am going to present a couple of interesting and lesser known uses of grep. I am not going to list grep options because this is what manpage is for but instead show a couple of neat things that can be achieved with grep that seem useful but are not so straightforward. Let’s get started:

Show colored matches and the entire input

Sometimes it’s handy to see all matches in color together with the entire original input on one screen. For example, we have a long text divided in many sections and we want to read the whole section that contains a given match. We don’t when in a section a match will occur. We can’t use -A or -B options because not sections are the same length. To achieve what we want we can use grep like this:

$ man grep | grep --color=always -E 'pattern|' | less

This command will show the entire grep manpage will all occurrences of `pattern` in color.

Start grepping from nth line:

Sometimes we want to start grepping a file from n-th line, for example to omit a pre-defined header we don’t care about. We can do achieve that with a little help of `tail`. For example, to start searching for a string from 15th line:

$ tail +15 FILE | grep <PATTERN>

Detect line endings in a file:

We can use grep to detect line endings:

$ egrep -l $'\r'\$ *

The above command will return success if file contains carriage returns, that line endings used in Windows world. Note though that $’r‘ is a bash feature and might non work in other shells.

Kategoriencli, grep, linux Tags: