Gary
Gary

Reputation: 129

Grep the line number for multiple occurences of the same string

I have a file containing data like this:

Index: ....
bla
bla
bla
Index: ....
bla
bla
bla
Index: ....
bla
bla
bla

Is there a way I can get the line number for each occurrence of Index: and then add this number to an array containing the line number of each occurrence of Index:

Upvotes: 0

Views: 42

Answers (1)

randomir
randomir

Reputation: 18687

You can do it easily with grep -n & cut:

arr=( $(grep -n Index file | cut -d: -f1) )

but even easier with awk:

arr=( $(awk '/Index/ {print NR}' file) )

In both cases the shell array arr will hold line numbers the Index appears on in file.

Upvotes: 2

Related Questions