grep有限的字符 - 一行

Pat*_*iel 21 unix linux ubuntu debian

我想在多个文件中查找单词,并且每个结果只返回一行,或者返回有限数量的字符(例如40~80个字符),而不是整行,默认情况下.

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 
Run Code Online (Sandbox Code Playgroud)

目前我看到以下内容:

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.
Run Code Online (Sandbox Code Playgroud)

aem*_*mus 18

你可以使用grep和cut的组合

使用你的例子我将使用:

grep -sRn 'wp-content' .|cut -c -40
grep -sRn 'wp-content' .|cut -c -80
Run Code Online (Sandbox Code Playgroud)

那将分别给你前40或80个字符.

编辑:

另外,grep中有一个标志,你可以使用:

-m NUM, --max-count=NUM
          Stop reading a file after NUM matching lines.
Run Code Online (Sandbox Code Playgroud)

这与我之前写的结合:

grep -sRnm 1 'wp-content' .|cut -c -40
grep -sRnm 1 'wp-content' .|cut -c -80
Run Code Online (Sandbox Code Playgroud)

这应该是第一次出现在每个文件,只有前40或80个字符.

  • 我真的更喜欢这个选项,因为你不需要修改你的正则表达式。 (2认同)

use*_*own 17

 egrep -Rso '.{0,40}wp-content.{0,40}' *.sh
Run Code Online (Sandbox Code Playgroud)

这不会叫Radio-Symphonie-Orchestra,但是-o(nly matching).

模式前后最多40个字符.注意:*e*grep.

  • `egrep` 现已弃用。请改用“grep -E”。 (3认同)