10

The use case is that I am searching for a particular CSS attribute in a directory of HTML/CSS/JS files (including sub-directories). Some one-liner JS libraries also have the CSS attribute that I'm searching for.

So is there a way to tell grep that it should not give result on a line which is longer than my defined $max_line_length?

2 Answers 2

13

First approach, try to exclude the one-liner JS files from being grepped in the first place. Often these will have a name like some-library.min.js, so you could do something like:

$ grep --exclude '*.min.js' ...

Another approach is that if you know that it's going to be in a CSS file, you can use ack to restrict your search to CSS files (and ignore various VCS cruft):

$ ack --type=css ...

However, to answer your question, you can write a regular expression to match on line length. The following will match any line with 100 or fewer characters.

$ grep -E '^.{,100}$'
3
  • 2
    +1 ack-grep on some systems Jul 14, 2012 at 11:38
  • 1
    Also, ack will ignore minified Javascript files. It sees them as not being source code, and so ignores. Jul 23, 2012 at 14:07
  • 2
    My grep only worked with {0,100} for some reason.
    – temoto
    Jan 30, 2013 at 12:34
1

I prefer to pipe through cut to cut the lines amd invert match -v to exclude stuff. Better readable to me. I guess perfomance wise not optimal

grep -r something . | cut -b 1-99 | grep -v min.js
1
  • They don't want to cut the lines, they want exclude lines longer than $max_line_length
    – Toto
    Jan 23, 2020 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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