[英]How to replace a specific line in a file with a string variable using the line number bash script?
[英]Using Bash Script to Find Line Number of String in File
如何使用bash脚本查找字符串出现的行号?
例如,如果文件看起来像这样,
Hello I am Isaiah
This is a line of text.
This is another line of text.
我运行脚本来查找字符串“line”,它将输出数字2,因为它是第一次出现。
鉴于您的示例仅打印第一次出现的字符串的行号,您可能正在寻找:
awk '/line/{ print NR; exit }' input-file
如果您确实想要所有出现(例如,如果您的示例的所需输出实际上是“2 \\ n3 \\ n”),请省略exit
。
我喜欢Siddhartha对OP的评论。 为什么他没有把它作为答案发布,这让我感到安慰。
我通常只想要显示我正在寻找的第一行的行号。
lineNum="$(grep -n "needle" haystack.txt | head -n 1 | cut -d: -f1)"
解释:grep的后,抓住只是第一行(NUM:线 ),由结肠d elimiter 切割并抓住第一架F ield
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.