如何在文件中出现字符串的地方打印行号? [英] How to print the line number where a string appears in a file?

查看:140
本文介绍了如何在文件中出现字符串的地方打印行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定的单词,我想找出文件中该单词出现的行号.

I have a specific word, and I would like to find out what line number in my file that word appears on.

这是在c shell脚本中发生的.

This is happening in a c shell script.

我一直在尝试与awk一起找到行号,但是到目前为止,我还没能找到.我也想将该行号分配给变量.

I've been trying to play around with awk to find the line number, but so far I haven't been able to. I want to assign that line number to a variable as well.

推荐答案

使用grep

要在文件中查找word并打印行号,请在grep中使用-n选项:

Using grep

To look for word in file and print the line number, use the -n option to grep:

grep -n 'word' file

这将同时打印行号及其匹配的行.

This prints both the line number and the line on which it matches.

这将打印文件中出现word字的行数:

This will print the number of line on which the word word appears in the file:

awk '/word/{print NR}' file

这将同时打印行号和出现word的行:

This will print both the line number and the line on which word appears:

awk '/word/{print NR, $0}' file

您可以用任何所需的正则表达式替换word.

You can replace word with any regular expression that you like.

工作原理:

  • /word/

这将选择包含word的行.

{print NR}

对于选定的行,这将打印行号(NR表示记录编号).您可以更改它以打印您感兴趣的任何信息.因此,{print NR, $0}将打印行号,然后是行本身$0.

For the selected lines, this prints the line number (NR means Number of the Record). You can change this to print any information that you are interested in. Thus, {print NR, $0} would print the line number followed by the line itself, $0.

使用命令替换:

n=$(awk '/word/{print NR}' file)

使用shell变量作为模式

假设我们要查找的正则表达式位于shell变量url中:

awk -v x="$url" '$0~x {print NR}' file

并且:

n=$(awk -v x="$url" '$0~x {print NR}' file)

这篇关于如何在文件中出现字符串的地方打印行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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