Patrick Maciel
Patrick Maciel

Reputation: 4944

grep limited characters - one line

I want to look up a word in multiple files, and return only a single line per result, or a limited number of characters (40 ~ 80 characters for example), and not the entire line, as by default.

grep -sR 'wp-content' .

file_1.sql:3309:blog/wp-content 
file_1.sql:3509:blog/wp-content 
file_2.sql:309:blog/wp-content 

Currently I see the following:

grep -sR 'wp-content' .

file_1.sql:3309:blog/wp-content-Progressively predominate impactful systems without resource-leveling best practices. Uniquely maximize virtual channels and inexpensive results. Uniquely procrastinate multifunctional leadership skills without visionary systems. Continually redefine prospective deliverables without.
file_1.sql:3509:blog/wp-content-Progressively predominate impactful systems without resource-leveling best practices. Uniquely maximize virtual channels and inexpensive results. Uniquely procrastinate multifunctional leadership skills without visionary systems. Continually redefine prospective deliverables without. 
file_2.sql:309:blog/wp-content-Progressively predominate impactful systems without resource-leveling best practices. Uniquely maximize virtual channels and inexpensive results. Uniquely procrastinate multifunctional leadership skills without visionary systems. Continually redefine prospective deliverables without.

Upvotes: 26

Views: 24486

Answers (3)

Tim Pote
Tim Pote

Reputation: 28039

If you change the regex to '^.*wp-content' you can use egrep -o. For example,

egrep -sRo '^.*wp-content' .

The -o flag make egrep only print out the portion of the line that matches. So matching from the start of line to wp-content should yield the sample output in your first code block.

Upvotes: 4

aemus
aemus

Reputation: 723

You could use a combination of grep and cut

Using your example I would use:

grep -sRn 'wp-content' .|cut -c -40
grep -sRn 'wp-content' .|cut -c -80

That would give you the first 40 or 80 characters respectively.

edit:

Also, theres a flag in grep, that you could use:

-m NUM, --max-count=NUM
          Stop reading a file after NUM matching lines.

This with a combination of what I previously wrote:

grep -sRnm 1 'wp-content' .|cut -c -40
grep -sRnm 1 'wp-content' .|cut -c -80

That should give you the first time it appears per file, and only the first 40 or 80 chars.

Upvotes: 23

user unknown
user unknown

Reputation: 36229

 egrep -Rso '.{0,40}wp-content.{0,40}' *.sh

This will not call the Radio-Symphonie-Orchestra, but -o(nly matching).

A maximum of 40 characters before and behind your pattern. Note: *e*grep.

Upvotes: 21

Related Questions