Let's say I have multiple lines similar to below in a file. Turbo is a cat. cats are good. cats are not dog.Coco is a black cat. cats are furry. cats are not dog.now, if want to grep all the ^.*cat but want to specially mention to capture till first (or nth) occurrence of the word cat.Desired Output:Turbo is a catCoco is a black cat*blah is a so and so cat*How can I grep it?PS: I would love to have an answer using grep (or its other variants) only.PS: I don't want to grep ^.*cat. and then do any operation  to remove the  .  . I want a generic answer.
Print up to (and including) the nth occurence of a pattern in a line
text processing;grep;regular expression;pcregrep
With POSIX grep, you can only choose between printing the whole line, or not printing the line content at all. If you want to transform the line, you need to use another tool such as sed or awk. To print up to the first occurrence of cat:sed -n 's/cat.*/cat/'awk 'sub(/cat.*/,)'Printing up to the Nth occurrence is more complicated.sed -n 's/cat/&\/3; T; P'awk 'gsub(/cat/,&\n) >= 3 {split($0, a, \n); printf %s%s%s\n, a[1], a[2], a[3]}'With GNU grep, you can use the -o option to print only the matched part of the line. Use the -P option to activate Perl syntax, so that non-greedy quantifiers are available.grep -P -o '^(.*?cat){1}'Replace the number in braces by the number n of the last occurrence of cat to be printed.While it's possible to express the same thing with extended regular expressions (-E), this requires a complex regexp, whose size is exponential in the size of the part to count (cat here).