David
David

Reputation: 3105

Unix find line number of a string in a file using awk/grip

I'm trying to find a position of a string

awk -F : '{if ( $0 ~ /Red Car/) print $0}' /var/lab/lab2/rusiuot/stud2001 | tail -l

and somehow I need to find a line position of Red Car. It is possible to do that using awk or grep?

Upvotes: 2

Views: 2208

Answers (2)

Jotne
Jotne

Reputation: 41446

You can do

awk '/Red Car/ {print NR}' /var/lab/lab2/rusiuot/stud2001

This will print the line number for the line with Red Car


If you like the line number to be printed at end of the file:

awk '/Red Car/ {a[NR]} 1; END {print "\nlines with pattern";for (i in a) printf "%s ",i;print ""}' file

Upvotes: 2

SMA
SMA

Reputation: 37023

Try something like:

grep -n "Red Car" /var/lab/lab2/rusiuot/stud2001 | cut -d":" -f 1

-n option will display the line number along with line where pattern is found.

Upvotes: 1

Related Questions