简体   繁体   English

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

[英]Using Bash Script to Find Line Number of String in File

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

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

I like Siddhartha's comment on the OP. 我喜欢Siddhartha对OP的评论。 Why he didn't post it as an answer escapes me. 为什么他没有把它作为答案发布,这让我感到安慰。

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 d elimiter and grab the first f ield 解释:grep的后,抓住只是第一行(NUM:线 ),由结肠d elimiter 切割并抓住第一架F ield

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM