简体   繁体   中英

Using Bash Script to Find Line Number of String in File

How can I use a bash script to find the line number where a string occurs?

For example if a file looked like this,

Hello I am Isaiah
This is a line of text.
This is another line of text.

and I ran the script to look for the string "line" it would output the number 2, as it is the first occurance.

Given that your example only prints the line number of the first occurrence of the string, perhaps you are looking for:

awk '/line/{ print NR; exit }' input-file

If you actually want all occurrences (eg, if the desired output of your example is actually "2\\n3\\n"), omit the exit .

I like Siddhartha's comment on the OP. Why he didn't post it as an answer escapes me.

I usually just want the line number of the first line that shows what I'm looking for.

lineNum="$(grep -n "needle" haystack.txt | head -n 1 | cut -d: -f1)"

Explained: after the grep, grab just the first line ( num:line ), cut by the colon d elimiter and grab the first f ield

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