Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep limited characters - one line

Tags:

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. 
like image 846
Patrick Maciel Avatar asked May 07 '12 18:05

Patrick Maciel


People also ask

Does grep have a character limit?

A maximum of 40 characters before and behind your pattern.

How do I limit grep results?

You can use grep option -m 1 which stops reading the file after the first match. Doesn't help with big files if the pattern is not found.

What is grep in shell script?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.


1 Answers

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.

like image 158
aemus Avatar answered Sep 18 '22 15:09

aemus