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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20026370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:21:59  来源:igfitidea点击:

Using Bash Script to Find Line Number of String in File

linuxbashshellunixterminal

提问by David L. Rodgers

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,因为它是第一次出现。

采纳答案by William Pursell

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”),请省略exit.

回答by hanzo2001

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

我喜欢悉达多对 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), cutby the colon delimiter and grab the first field

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