0

Is there a way to instruct grep to cut results after X chars?

E.g. if I execute grep -iR searchString then sometimes there are compressed javascript files in the result where the whole code is in one line and this "destroys" the result because there is sometimes too much content for my terminal to handle and parts of the result dissapears or I have to scroll much.

e.g. the result should change from...

123456789

...to...

1234

...if I execute grep with the pseudo option --show-n-chars 4.

I searched in the documentation but I was unable to find something.

6

You could use option -o to only print the matching part in combination with -E (extended regular expression) and pattern .{0,4} to match up to four characters after your search pattern:

$ echo "foo123456789" | grep -oE 'foo.{0,4}'
foo1234

Or you could pipe the result to head -cN (similar to cut) to print N characters:

$ echo "foo123456789" | grep 'foo' | head -c4
foo1
1
  • I prefer this answer, because it uses the tool the op wanted to use.
    – thecarpy
    May 14 '19 at 8:58
1

grep itself has no such option. You can achieve your goal with the cut command:

grep "foo" bar | cut -c -4

This will only print the first 4 chars of every grep result.

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.