如何从grep获取行号?

UAd*_*ter 22 command-line grep

下面的grep

grep -r -e -n coll *
Run Code Online (Sandbox Code Playgroud)

会显示

fullpath/filename:  <tag-name>coll</tag-name>
Run Code Online (Sandbox Code Playgroud)

我想知道哪一行有以下文字,我尝试添加-n,但没有用。我尝试添加 | grep -n *,但它做了一些奇怪的事情。

我想看到的(我不在乎格式)是

fullpath/filename:10:  <tag-name>coll</tag-name>
Run Code Online (Sandbox Code Playgroud)

lga*_*rzo 19

您应该-e在选项列表的末尾放置:grep -rne coll *


Yun*_*nus 18

不需要 -r & -e !

获取模式的行号!

grep -n "pattern" file.txt
Run Code Online (Sandbox Code Playgroud)

如果您只想获取行号作为输出,请向其中添加另一个 grep 命令!

grep -n "pattern" file.txt | grep -Eo '^[^:]+'
Run Code Online (Sandbox Code Playgroud)

  • 要获得行号,使用 `cut` 更容易,例如 `cut -f1 -d:` (3认同)