如何在文件中出现字符串的地方打印行号? [英] How to print the line number where a string appears in a file?
问题描述
我有一个特定的单词,我想找出文件中该单词出现的行号.
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屋!