Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
2  
You could pipe it into cut but then you'd still lose the colors: grep -r "foo"|cut -c 1000. –  Andrew Lambert Feb 4 '12 at 6:27
1  
You could switch to a better tool :-) ack - grep on steroids and then use this answer stackoverflow.com/a/2034806/17413 –  Nifle Feb 4 '12 at 8:42

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Yes, I have set --color=auto in my .bashrc. Using --color=always with cut did the trick. –  Attila O. Feb 7 '12 at 2:49

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: http://unix.stackexchange.com/a/113507/48906

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.