Using Bash Script to Find Line Number of String in File
Solution 1:
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
.
Solution 2:
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 delimiter and grab the first field
Solution 3:
For an exact match, I use
grep -wn <your exact match word> inputfile | cut -d: -f1
Explained: -n print the line number -w to only return the line with exact match