使用Bash脚本查找文件中的字符串行数

Dav*_*ers 29 unix linux bash shell terminal

如何使用bash脚本查找字符串出现的行号?

例如,如果文件看起来像这样,

Hello I am Isaiah
This is a line of text.
This is another line of text.
Run Code Online (Sandbox Code Playgroud)

我运行脚本来查找字符串"line",它将输出数字2,因为它是第一次出现.

Wil*_*ell 47

鉴于您的示例仅打印第一次出现的字符串的行号,您可能正在寻找:

awk '/line/{ print NR; exit }' input-file
Run Code Online (Sandbox Code Playgroud)

如果您确实想要所有出现(例如,如果您的示例的所需输出实际上是"2 \n3 \n"),请省略exit.


han*_*001 7

我喜欢Siddhartha对OP的评论。为什么他没有将其发布为答案使我无所适从。

我通常只想要显示我要寻找的第一行的行号。

lineNum="$(grep -n "needle" haystack.txt | head -n 1 | cut -d: -f1)"
Run Code Online (Sandbox Code Playgroud)

解释: grep的,抓斗只是第一行之后(民:线),切割由结肠d elimiter并抓取第一˚F ield

  • `head -n 1` 可以替换为 `grep` 中的 `-m 1` 标志 (5认同)

Ahm*_*ndi 5

为了精确匹配,我使用

grep -wn <your exact match word> inputfile | cut -d: -f1
Run Code Online (Sandbox Code Playgroud)

解释: -n 打印行号 -w 仅返回完全匹配的行