简体   繁体   中英

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?

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

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.

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