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

时间:2022-04-11 19:27:03

How can I use a bash script to find the line number where a string occurs?

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

For example if a file looked like this,

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

Hello I am Isaiah
This is a line of text.
This is another line of text.

and I ran the script to look for the string "line" it would output the number 2, as it is the first occurance.

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

2 个解决方案

#1


31  

Given that your example only prints the line number of the first occurrence of the string, perhaps you are looking for:

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

awk '/line/{ print NR; exit }' input-file

If you actually want all occurrences (eg, if the desired output of your example is actually "2\n3\n"), omit the exit.

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

#2


1  

I like Siddhartha's comment on the OP. Why he didn't post it as an answer escapes me.

我喜欢Siddhartha对OP的评论。为什么他没有发布它作为答案逃脱了我。

I usually just want the line number of the first line that shows what I'm looking for.

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

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

Explained: after the grep, grab just the first line (num:line), cut by the colon delimiter and grab the first field

解释:在grep之后,抓住第一行(num:line),用冒号分隔符剪切并抓住第一个字段

#1


31  

Given that your example only prints the line number of the first occurrence of the string, perhaps you are looking for:

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

awk '/line/{ print NR; exit }' input-file

If you actually want all occurrences (eg, if the desired output of your example is actually "2\n3\n"), omit the exit.

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

#2


1  

I like Siddhartha's comment on the OP. Why he didn't post it as an answer escapes me.

我喜欢Siddhartha对OP的评论。为什么他没有发布它作为答案逃脱了我。

I usually just want the line number of the first line that shows what I'm looking for.

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

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

Explained: after the grep, grab just the first line (num:line), cut by the colon delimiter and grab the first field

解释:在grep之后,抓住第一行(num:line),用冒号分隔符剪切并抓住第一个字段