shell脚本查找字符串的第n个出现位置并打印行号 [英] shell script to find the nth occurrence of a string and print the line number

查看:560
本文介绍了shell脚本查找字符串的第n个出现位置并打印行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为hello的文件,其中包含以下数据

I have a file named hello with the following data

onefish
onechicken
twofish
twochicken
threechicken
twocows

我想获取第二次出现chicken的行号.

I want to get the line number at which chicken is occurring for the second time.

在第4行中第二次出现chicken时,输出应为"4".

Output should be "4" as chicken occurs for the second time in 4th line.

推荐答案

您可以为此使用awk:

You can use awk for this:

awk '/chicken/{++n; if (n==2) { print NR; exit}}' file

4

这篇关于shell脚本查找字符串的第n个出现位置并打印行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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