使用 Bash 脚本查找文件中字符串的行号 [英] Using Bash Script to Find Line Number of String in File

查看:19
本文介绍了使用 Bash 脚本查找文件中字符串的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

For example if a file looked like this,

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

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

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

推荐答案

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

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

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

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

这篇关于使用 Bash 脚本查找文件中字符串的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆