Roy Chan
Roy Chan

Reputation: 51

How to return the line number of the first occurrence of a text in a file in linux

How to return the line number of the first occurrence of a text in a file in linux? For instance, a file as follows.

12:04:56 xxxx
12:06:23 xxxx
12:09:11 xxxx
12:09:13 xxxx
12:10:12 xxxx

Can anyone provide a line command which returns 3 if the desire text is "12:09:"?

Upvotes: 5

Views: 3973

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 184975

Try this :

awk '/12:06:23/{print NR;exit}' file

and with and :

grep -n -m1 "12:06:23" file | cut -d':' -f1

Upvotes: 7

Mureinik
Mureinik

Reputation: 311053

grep -n return also the line number of the found match. From there on, you can use a combination of head and cut to extract just the line number:

cat myfile.txt | grep -n "12:09" | head -1 | cut -d":" -f1

Upvotes: 1

Related Questions