Using Bash Script to Find Line Number of String in File

70,787

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

Share:
70,787

Related videos on Youtube

David L. Rodgers
Author by

David L. Rodgers

Updated on July 09, 2022

Comments

  • David L. Rodgers
    David L. Rodgers almost 2 years

    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.

    • Siddhartha
      Siddhartha over 10 years
      You could just do grep -n "line" file.txt and it'll give you the line numbers.
    • Siddhartha
      Siddhartha over 10 years
      Also grep --color=always -n "line" file.txt will highlight in red the occurences of the word 'line'
  • Farhan Ahmed Wasim
    Farhan Ahmed Wasim over 9 years
    I have tried using the above command, with the string 'line' stored in a variable. I had read somewhere, that when we are trying to use an external variable within an awk command, it is good to first assign the external variable to a local awk variable. As such I tried the following command: awk -v var="$external_variable" '/external_variable/{ print NR; exit }' input-file but the command didn't return the line number. Can you tell me what I am doing wrong?
  • William Pursell
    William Pursell over 9 years
    You need to use match rather than //. For example: awk 'match($0,v){print NR; exit}' v=$external_variable input-file should work.
  • i spin and then i lock
    i spin and then i lock over 2 years
    head -n 1 can be replaced with -m 1 flag in grep