How to limit the number of characters returned by each match in grep

Viewed 82

How can I limit the results shown by grep -rn "sqs" * to exclude long results (more than say a line or two long)?

2 Answers

You may try this find + awk:

find . -type f -exec awk 'length() <= 80 && /sqs/ {
print FILENAME ":" FNR ":\033[1;31m" $0 "\033[0m "}' {} +
  • length() <= 80 will search sqs string in lines that have 80 or less characters in them.
  • "\033[1;31m" $0 "\033[0m " is used to color the line red.

Use grep followed by filtering in Perl, and finally, use the grep only to add back the coloring (otherwise, it does not do anything useful, since all lines should match):

grep -rn 'sqs' * | perl -ne 'print if length $_ <= 30' | grep 'sqs'
Related