6

How do I exclude very long lines from grep results?

I often grep through lots of .js files (-r) and some of them are compiled, so they consist of a single line usually a couple thousand characters long. From all that clutter I find it hard to see the results from the rest of the files.

What should I pass to grep to exclude lines that are, say, more than 1000 character long?

I'd prefer not having to pipe the result through another grep, as that would make me lose colours from the output, or having to add the first grep at the end of the pipe again to get back the colours.

2

2 Answers 2

5

Piping the grep to something won't necessarily get rid of the colors. That behavior results from --color=auto (which if you check alias grep is probably what you're using). You can override it and pass --color=always and grep will preserve the colors even through a pipe.

As far as excluding the lines, you could pipe to whatever tool you like (e.g. cut as Amazed mentioned). Keep in mind, that the colors from grep will insert extra bytes into the matched lines, if that matters to you. There's no obvious way to (to me anyway) do it in the same grep invocation.

2
  • Yes, I have set --color=auto in my .bashrc. Using --color=always with cut did the trick.
    – Attila O.
    Commented Feb 7, 2012 at 2:49
  • Does the cut command not just output the specified characters from each line, not omit those lines? (i.e. chars 1-1000) Commented Oct 9, 2018 at 4:43
3

The following command should achieve what you want, i.e. do not output matching lines whose length is greater than 1000 characters:

grep -r --color=always $pattern . | cut -c1-1000

The --color=always flag ensure that color escape sequences will be generated by grep.

This option default value is --color=auto, which makes grep color its output only if it is passed to an interactive terminal, and does not use colors when it's piped to another command.

Source: https://unix.stackexchange.com/a/113507/48906

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .