Search code examples
grep

How can I filter matched lines by length using grep?


I want to filter out lines matched by grep such that lines longer than some maximum length are removed from match results.

An example use case for this is that I am using grep to find matches for a particular function call. I have a directory on a Linux server where I have a collection of code repositories. I know that I have previously written some code which uses a particular function, and that I could use as an example for something else.

I don't remember which directory this example code is, but I do know a function which I have used.

If I grep for matches without filtering long lines, I get a wall of text due to spurious matches.

I can't easily provide any examples of what I see on my screen - please just imagine that the output of grep includes some lines which are thousands of characters, and indeed thousands of lines long. Such lines obscure the output and make it impossible to read - hence I aim to filter them out.


Solution

  • The important grep string is grep '^\{1,200\}$', which means:

    • ^ anchor beginning of line
    • $ anchor end of line
    • .\{1,200\} match any character (.) from 1 to 200 times
    grep -rI some_function . 2>/dev/null | grep '^.\{1,200\}$'