简体   繁体   中英

shell script to find the nth occurrence of a string and print the line number

I have a file named hello with the following data

onefish
onechicken
twofish
twochicken
threechicken
twocows

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

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

You can use awk for this:

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

4
grep -n chicken hello| sed -n '2 s/:.*//p'

for fun, using pattern as separtor and counting on field

awk -F 'chicken' 'NF>1{if (2==++o)print NR}' YourFile

using sed (not appropriate compare to awk) [ ^J is CTRL+V+J, real new line]

sed -e '/chicken/H;g;s/\(\^J.*\)\{2\}//;t h' -e 'd' -e ':h' -e ' =;q' YourFile

shorter

$ awk '/chicken/ && ++n==2 {print NR}' file

if the input file is long, adding exit after printing will stop processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM